Reputation: 2537
This is my code:
$a = array(
array("a" => 1, "b" => 2),
array("x" => 2, "a" => 2),
array("d" => 100, "a" => 3, "b" => 2, "c" => 3)
);
$myArray = array();
foreach ($a as $arr) {
$myArray[] = $arr['a'];
}
print_r($myArray);
So, I get
Array
(
[0] => 1
[1] => 2
[2] => 3
)
Is there any other way to do this without for
loop? like using one are two PHP array functions
to get the same response.
The above is correct but still if there is any other better way to do this that would be appreciable! Because the same array $a
in my code is required to be iterate many times. If I have any better way to do this so I can reduce another iteration( PHP still does iteration in built-in fns, I don't bother it).
Upvotes: 0
Views: 2293
Reputation: 37365
Yes (since you're on PHP 5.4, array_column()
isn't an option),
$result = array_map(function($x)
{
return $x['a'];
}, $a);
But note, this will still use loop internally (i.e. in the end it always be a loop)
Upvotes: 3