How can I flatten a simple array without writing a loop operator explicitly?

arrays, foreach, loops, multidimensional-array, php

Solution

You could `map` it:

$arr = array_map(function($element) {
    return $element['id'];
}, $arr);

Since `array_map` probably internally loops, you could do it truly without looping:

$arr = array_reduce($arr, function($arr, $element) {
    $arr[] = $element['id'];
    return $arr;
});

But there's no reason to not loop. There's no real performance gain, and the readability of your code is arguably decreased.

Problem

I'd like to turn a simple multidimensional array into an even more simple array. Turn this: ``` Array ( [0] => Array ( [id] => 123 ) [1] => Array ( [id] => 456 ) ... [999] => Array ( [id] => 789 ) ) ``` Into an array like this: ``` Array ( [0] => 123 [1] => 456 ... [999] => 789 ) ``` I'd like to do so without foreach `foreach`. Is this possible in PHP? Here's how I can already solve it with a `foreach` loop: ``` $newArr = array(); foreach ($arr as $a) { $newArr[] = $a['id']; } $arr = $newArr; ``` I'd like to do it without looping. Can you help?

Original source

Related problems