Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I flatten a simple array without looping?

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?

like image 307
Ryan Avatar asked Jan 14 '23 04:01

Ryan


1 Answers

I admire your desire to have something approaching functional programming and implicit looping, but PHP is the wrong language for you. It does not express itself naturally in a functional style.

The reset function returns the first element in an array, so you can map that function over the array:

array_map('reset', $array)

However in PHP the fastest method is a simple for loop (not foreach, for). Here are a bunch of different methods of flattening. Only the functions containing for and foreach perform explicit looping and are included for comparison.

function flatten_for($arr) {
    $c = count($arr);
    $newarr = array();
    for ($i = 0; $i < $c; $i++) {
        $newarr[] = $arr[$i][0];
    }
    return $newarr;
}


function flatten_for_inplace($arr) {
    $c = count($arr);
    for ($i = 0; $i < $c; $i++) {
        $arr[$i] = $arr[$i][0];
    }
}


function flatten_foreach($arr) {
    $newarr = array();
    foreach ($arr as $value) {
        $newarr[] = $value[0];
    }
    return $newarr;
}

function flatten_foreach_inplace($arr) {
    foreach ($arr as $k => $v) {
        $arr[$k] = $v[0];
    }
}

function flatten_foreach_inplace_ref($arr) {
    foreach ($arr as &$value) {
        $value = $value[0];
    }
}

function flatten_map($arr) {
    return array_map('reset', $arr);
}

function flatten_walk($arr) {
    array_walk($arr, function(&$v, $k){$v = $v[0];});
}

function visitor($v, $k, &$a) {
    return $a[] = $v;
}

function flatten_walk_recursive($arr) {
    $newarr = array();
    array_walk_recursive($arr, 'visitor', $newarr);
    return $newarr;
}

function reducer($result, $item) {
    return $item[0];
}

function flatten_reduce($arr) {
    return array_reduce($arr, 'reducer', array());
}

function flatten_merge($arr) {
    return call_user_func_array('array_merge_recursive', $arr);
}

Here is the timing code:

function buildarray($length) {
    return array_map(function($e){return array($e);}, range(0, $length));
}

function timeit($callable, $argfactory, $iterations) {
    $start = microtime(true);
    for ($i = 0; $i < $iterations; $i++) {
        call_user_func($callable, call_user_func($argfactory));
    }
    return microtime(true) - $start;
}

function time_callbacks($callbacks, $argfactory, $iterations) {
    $times = array();
    foreach ($callbacks as $callback) {
        $times[$callback] = timeit($callback, $argfactory, $iterations);
    }
    return $times;
}

function argfactory() {
    return buildarray(1000);
}

$flatteners = array(
    'flatten_for', 'flatten_for_inplace', 'flatten_foreach',
    'flatten_foreach_inplace', 'flatten_foreach_inplace_ref',
    'flatten_map', 'flatten_walk', 'flatten_walk_recursive',
    'flatten_reduce', 'flatten_merge',
);

$results = time_callbacks($flatteners, 'argfactory', 1000);

var_export($results);

On an oldish MacBook Pro (Core 2 Duo, 2.66 GHz, 8GB, PHP 5.3.15 with Suhosin-Patch) I get these results:

array (
  'flatten_for' => 12.793387174606,
  'flatten_for_inplace' => 14.093497991562,
  'flatten_foreach' => 16.71691608429,
  'flatten_foreach_inplace' => 16.964510917664,
  'flatten_foreach_inplace_ref' => 16.618073940277,
  'flatten_map' => 24.578175067902,
  'flatten_walk' => 22.884744882584,
  'flatten_walk_recursive' => 31.647840976715,
  'flatten_reduce' => 17.748590946198,
  'flatten_merge' => 20.691106081009,
)

The difference between the for and foreach methods is smaller on longer arrays.

Surprisingly (to me, anyway) flatten_merge is still slower than a plain for loop. I expected array_merge_recursive to be at least as fast if not faster since it's basically handing the whole job off to a C function!

like image 137
Francis Avila Avatar answered Jan 18 '23 05:01

Francis Avila