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.
Either 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);
There is no major "performance" difference, because the differences are located inside the logic. You use foreach for array iteration, without integers as keys. You use for for array iteration with integers as keys. etc.
The forEach method is also used to loop through arrays, but it uses a function differently than the classic "for loop". The forEach method passes a callback function for each element of an array together with the following parameters: Current Value (required) - The value of the current array element.
In this program, foreach loop is used to traverse through a collection. Traversing a collection is similar to traversing through an array. The first element of collection is selected on the first iteration, second element on second iteration and so on till the last element.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With