Article
0 comment

Dereferencing deeply nested arrays with array_reduce

Sometimes you need to grab a value from a deeply nested array and you get a path description to that value as a string. For example you get a path as

$path = “A.B.C.D.X”;

which refers to a value in an array like this:

$param[‘A’][‘B’][‘C’][‘D’][‘X’] = “Dorky”;

Now you would like to get the value “Dorky” only by using the string description in $path. You need to get every indexing step as a string value by exploding the string at the “.” characters.

$patharray = explode(”.”, $path);

Then you need to go along this path in array form and dereference the $param array down to its value. You could do so with a foreach loop on the $path array. But you can do it more elegant using array_reduce.
Normally array_reduce iterates over an array and gathers (in any sense) information to sum it up in some single value. But you can also replace this “sum variable” by something else. For example by a dereferenced value of an array … you get a clue?
And since we don’t want to pollute our namespaces with callback functions, why not use the new PHP5.3 feature of anonymous functions?
Putting it all together leads to a one liner:

$value = array_reduce(explode(’.’, $str), function($v, $w) { return $v[$w]; }, $param);

To try it out here is the complete script:

<?php
$str=“A.B.C.D.X”;
$param[‘A’][‘B’][‘C’][‘D’][‘X’]=“Dorky”;
$value=array_reduce(explode(’.’, $str), function($v, $w) { return $v[$w]; }, $param);
print_r($value);
?>

Have fun!