Getting array values ​​without foreach loop

Is there a way to get all the values ​​in one array without using foreach loops in this example?

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

I need the result of array("a", "b", "c")

I could accomplish this using something like this

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

But I'm looking for options that are not related to using foreach loops.

+6
source share
2 answers

If you are using PHP 5.5+, you can use array_column() , for example:

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

If you need an array with numeric indices, use:

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

If you are using a previous version of PHP and cannot upgrade it at this time, you can use the Userland Implementation array_column() function, written by the same author.

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

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

Use array_column() for PHP 5.5:

 $foo = array(["type"=>"a"], ["type"=>"b"], ["type"=>"c"]); $result = array_column($foo, 'type'); 

Or use array_map() for previous versions:

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

Note. The loop will still execute, but it will be hidden inside the above functions.

+4
source

All Articles