Skip to content
Advertisement

PHP: Use Variable as Multiple Keys in Multi-Dimensional-Array

In a normal array you can select this way

$key='example';
echo $array[$key];

How about in a multidimensional?

$keys='example[secondDimension][thirdDimension]';
echo $array[$keys];

What’s the proper way to go about this?

Advertisement

Answer

i think this solution is good.

note that you have to wrap all keys with “[” and “]”.

$array = array(
    'example' => array(
        'secondDimension' => array(
            'thirdDimension' => 'Hello from 3rd dimension',
        )
    ),
);

function array_get_value_from_plain_keys($array, $keys)
{
    $result;

    $keys = str_replace(array('[', ']'), array("['", "']"), $keys); // wrapping with "'" (single qoutes)

    eval('$result = $array' . $keys . ';');

    return $result;
}

$keys = '[example][secondDimension][thirdDimension]'; // wrap 1st key with "[" and "]"
echo array_get_value_from_plain_keys($array, $keys);

Learn more about eval() function

if you also want to check if the value is defined or not then you can use this function

function array_check_is_value_set_from_plain_keys($array, $keys)
{
    $result;

    $keys = str_replace(array('[', ']'), array("['", "']"), $keys); // wrapping with "'" (single qoutes)

    eval('$result = isset($array' . $keys . ');');

    return $result;
}

Giving a better name to that function will be appreciated ^^

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement