php call array from string

后端 未结 4 397
面向向阳花
面向向阳花 2021-01-23 02:57

I have a string that contains elements from array.

$str = \'[some][string]\';
$array = array();

How can I get the value of $array[\'some\

4条回答
  •  深忆病人
    2021-01-23 03:48

    You can do so by using eval, don't know if your comfortable with it:

    $array['some']['string'] = 'test';    
    $str = '[some][string]';    
    $code = sprintf('return $array%s;', str_replace(array('[',']'), array('[\'', '\']'), $str));    
    $value = eval($code);    
    echo $value; # test
    

    However eval is not always the right tool because well, it shows most often that you have a design flaw when you need to use it.

    Another example if you need to write access to the array item, you can do the following:

    $array['some']['string'] = 'test';
    $str = '[some][string]';
    $path = explode('][', substr($str, 1, -1));
    $value = &$array;
    foreach($path as $segment)
    {
        $value = &$value[$segment];
    }
    
    echo $value;
    $value = 'changed';
    print_r($array);
    

    This is actually the same principle as in Eric's answer but referencing the variable.

提交回复
热议问题