Php call array from string

I have a string containing elements from an array.

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

How can I get the value of $array['some']['string'] using $str ?

+2
source share
4 answers

You can do this using eval, you don’t know if it’s convenient for you:

 $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 most often shows that you have a design flaw when you need to use it.

Another example, if you need to write access to an array element, 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 Eric's answer , but referring to a variable.

+3
source

This will work for any number of keys:

 $keys = explode('][', substr($str, 1, -1)); $value = $array; foreach($keys as $key) $value = $value[$key]; echo $value 
+4
source
 // trim the start and end brackets $str = trim($str, '[]'); // explode the keys into an array $keys = explode('][', $str); // reference the array using the stored keys $value = $array[$keys[0][$keys[1]]; 
+1
source

I think regexp should do the trick better:

 $array['some']['string'] = 'test'; $str = '[some][string]'; if (preg_match('/\[(?<key1>\w+)\]\[(?<key2>\w+)\]/', $str, $keys)) { if (isset($array[$keys['key1']][$keys['key2']])) echo $array[$keys['key1']][$keys['key2']]; // do what you need } 

But I would think twice before handling arrays in my own way: D

0
source

Source: https://habr.com/ru/post/914995/


All Articles