Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Is there any way to get all values in one array without using foreach loops, in this example?

<?php 
$foo = array(["type"=>"a"], ["type"=>"b"], ["type"=>"c"]);

The output I need is array("a", "b", "c")

I could accomplish it using something like this

$stack = [];

foreach($foo as $value){
  $stack[] = $value["type"];
}

var_dump($stack); 

But, I am looking for options that does not involve using foreach loops.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
212 views
Welcome To Ask or Share your Answers For Others

1 Answer

If you're using PHP 5.5+, you can use array_column(), like so:

$result = array_column($foo, 'type');

If you want an array with numeric indices, use:

$result = array_values(array_column($foo, 'type'));

If you're using a previous PHP version and can't upgrade at the moment, you can use the Userland implementation of array_column() function written by the same author.

Alternatively, you could also use array_map(). This is basically the same as a loop except that the looping is not explicitly shown.

$result = array_map(function($arr) {
   return $arr['type'];
}, $foo);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...