0

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).

5

1 Answer 1

3

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)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.