Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 777
Button 108 Avatar asked Nov 26 '22 03:11

Button 108


1 Answers

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 ^^

like image 152
Abdullah Mallik Avatar answered Dec 06 '22 00:12

Abdullah Mallik