Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - Using stored value as array key

Tags:

arrays

php

PHP has a handy feature to allow to "pre-create" array keys in a form:

<input type="text" name="settings[store][this][here]" />

Now, in a database I have stored the "location" of a certain value, using this field value:

[store][this][here]

I want to recall this value in an array call, like this:

echo $result[settings][database-field];

which would then become:

echo $result[settings][store][this][here];

How can I construct my call to do this?

I have tried the following, but to no avail:

echo $result[settings][$row[database-field]];
echo $result[settings][${$row[database-field]}]
like image 600
Taapo Avatar asked Jun 15 '26 14:06

Taapo


1 Answers

You could use regular expressions to parse the keys from the location (parsing will dynamically adapt to keys of different depths > 0):

$result['settings'] = ['store'=>['this'=>['here'=>'stored value']]];
$location = "[store][this][here]";

preg_match_all('/\[(\w+)\]/',$location, $matches);
$keys = $matches[1];

$value = $result['settings'][current($keys)];
while(next($keys)) $value = $value[current($keys)];

echo $value; // 'stored value'

demo

I would be careful about using eval() on user-supplied input.

like image 92
BeetleJuice Avatar answered Jun 17 '26 02:06

BeetleJuice