Jimmy Howe
Jimmy Howe

Reputation: 185

Using a path to an array item

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.

Upvotes: 1

Views: 194

Answers (1)

Fabian Schmengler
Fabian Schmengler

Reputation: 24551

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.

Upvotes: 4

Related Questions