How to use a string as an array index path to retrieve a value? How to use a string as an array index path to retrieve a value? arrays arrays

How to use a string as an array index path to retrieve a value?


A Bit later, but... hope helps someone:

// $pathStr = "an:string:with:many:keys:as:path";$paths = explode(":", $pathStr); $itens = $myArray;foreach($paths as $ndx){    $itens = $itens[$ndx];}

Now itens is the part of the array you wanted to.

[]'s

Labs


you might use an array as path (from left to right), then a recursive function:

$indexes = {0, 'Data', 'name'};function get_value($indexes, $arrayToAccess){   if(count($indexes) > 1)     return get_value(array_slice($indexes, 1), $arrayToAccess[$indexes[0]]);   else    return $arrayToAccess[$indexes[0]];}


This is an old question but it has been referenced as this question comes up frequently.

There are recursive functions but I use a reference:

function array_nested_value($array, $path) {    $temp = &$array;    foreach($path as $key) {        $temp =& $temp[$key];    }    return $temp;}$path  = array(0, 'Data', 'Name');$value = array_nested_value($array, $path);