skip to Main Content

I have a given path with keys (in a separate array) to a subarray within a multidimensional one.

$path_array = array( 'first', 'new', 'best');
$multi_data = array(
  'first' => array(
    'example' => 'good',
    'other' => 'well',
    'new' => array(
      'subset' => 'none',
      'best' => 'stackoverflow',
    )
   )
);

The arrays are changing of course due to dynamically generated data.

My Question: How to get the correct value or array by the path that i have got?
A correct static approach would be:

echo $multi_data['first']['new']['best'];
// prints: stackoverflow

I tried foreach-Loop on $path_array, but i cant put the path elements together (keys is square brackets).

2

Answers


  1. EDIT: don’t know why I went through all this trouble with shifting values, foreach works just fine

    Could do something like:

    $result = $multi_data;
    foreach($path_array as $key){
        $result = $result[$key];
    }
    echo $result;
    

    The idea is to get deeper into the array with each iteration. Be extra careful if you might have some non-existent keys, though.

    Login or Signup to reply.
  2. I suggest this recursive function:

    function array_get_from_path(array &$arr, array $path = []): mixed {
        if (empty($path))
            return $arr;
        
        $key = array_shift($path);
        
        if (!is_array($arr) || !array_key_exists($key, $arr))
            throw new Exception('path does not exist.');
        
        if (empty($path))
            return $arr[$key];
        
        return array_get_from_path($arr[$key], $path);    
    }
    

    demo

    Note that the first parameter &$arr is a reference to the data array to avoid a copy of the array at each call of the function. But the final return (the string "stackoverflow" in your example) is a copy. In other words, if you call the function like that:

    $result = array_get_from_path($multi_data, $path_array);
    

    and then you change the value of $result:

    $result = 'bar';
    

    the value inside the array doesn’t change.

    But if you want the function returns a reference (useful to edit the array data), you have to change the function declaration like that:

    function &array_get_from_path(array &$arr, array $path = []): mixed {
        // ...
    }
    

    and to also call it with an ampersand:

    $result = &array_get_from_path($multi_data, $path_array);
    

    This time, if you change $result, it will also change the value in the array, because it’s no more a copy but a reference to the data in the array.

    demo

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search