1

Is there a way to reference an item within a multidimensional array by using a path or an array of path elements? EG.

$multi = array
(
    'array_1' => array
    (
        'array_2' => array
        (
            'option_1' => 'value_1',
            'option_2' => 'value_2',
        )
    )
);

$path = array('level_1', 'level_2', 'option_1');
$result = $multi[$path];

And have $result = 'value_1'?

The reason being, I have a recursive function for searching thru $multi and finding the key I need, and returning the $path. I know i can hard code in the path from my own code but i'm trying to make this reusable so that i can edit the $multi and the function will still work.

2
  • Your question is unclear to me. Please show exactly what you are trying to achieve Commented Feb 10, 2013 at 15:02
  • Won't $result = $multi['array_1']['array_2']['option_1']; do the trick? Commented Feb 10, 2013 at 15:07

1 Answer 1

4

There's nothing built into PHP to do this but you can write a function for it, using a moving reference:

/**
 * @param string $path path in the form 'item_1.item_2.[...].item_n'
 * @param array $array original array
 */
function &get_from_array($path, &$array)
{
    $current =& $array;
    foreach(explode('.', $path) as $key) {
        $current =& $current[$key];
    }
    return $current;
}

Example:

// get element:
$result = get_from_array('level_1.level_2.option_1', $multi);
echo $result; // --> value_1

$result = 'changed option';
echo $multi['level_1']['level_2']['option_1']; // --> changed_option

I wrote it to convert names from configuration files to arrays, if you want to pass the path itself as an array like in your example, just leave out the explode.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.