PHP Add element to every sub array of multi dimension array

Whatever speed one might hope to gain by using array_walk, is lost with function overhead. Since you stated in your comments that the array is a result of a db query, you can simply include the bag value in your result set by adding SELECT 'bag' AS 'type' to your SQL statement.

$start = 0; $end = 0;

$orig = array(
    array('id' => 1,  'title' => 'title 1'),
    array('id' => 10, 'title' => 'title 10'),
    array('id' => 11, 'title' => 'title 11')
);

// A
$start = microtime(true);
for ($a=0; $a<1000; $a++) {
    $els1 = $orig;
    array_walk($els1, function(&$val, $key){$val['type'] = 'bag';});
}
$end = microtime(true);
echo 'A: ', $end - $start,  "<br />\n";

// B
$start = microtime(true);
for ($b=0; $b<1000; $b++) {
    $els2 = $orig;
    foreach ($els2 as &$el) {
        $el['type'] = 'bag';
    }
    unset($el);
}
$end = microtime(true);
echo 'B: ', $end - $start,  "<br />\n";

/* output:

A: 0.0076138973236084
B: 0.0047528743743896

A: 0.0075309276580811
B: 0.0045361518859863

A: 0.0075531005859375
B: 0.062379837036133

A: 0.0075340270996094
B: 0.0044951438903809

A: 0.0074868202209473
B: 0.0044751167297363

A: 0.0076088905334473
B: 0.0048189163208008

*/

Leave a Comment