Scott Foster
Scott Foster

Reputation: 485

How can I use a string within the tree of an array in PHP?

I am getting the path to a value in PHP, but not sure how to combine the array with a stringed path? The following gives me a value.

var_dump($array['boo']['far'][0]); // works

While none of these give me a valid (or are even valid PHP).

$path = "['boo']['far'][0]";
var_dump($array.$path); // doesn't work
var_dump($array{$path}); // doesn't work
var_dump(eval($array.$path)); // doesn't work

Any ideas?

Upvotes: 0

Views: 66

Answers (2)

Nick
Nick

Reputation: 147206

If your string components of the path are fairly simple, you could parse the path into components using preg_match_all and then recursively go through the levels of the array to find the desired element:

$array['boo']['far'][0] = "hello world!\n";
$path = "['boo']['far'][0]";

preg_match_all("/\['?([^\]']+)'?\]/", $path, $matches);
$v = $array;
foreach ($matches[1] as $p) {
    $v = $v[$p];
}
echo $v;

Output:

hello world!

Demo on 3v4l.org

Other than that, your only real alternative is eval. You can use eval to echo the value, or to assign it to another variable. For example,

$array['boo']['far'][0] = "hello world!\n";
$path = "['boo']['far'][0]";
eval("echo \$array$path;");
eval("\$x = \$array$path;");
echo $x;
$y = eval("return \$array$path;");
echo $y;

Output:

hello world!
hello world!
hello world!

Demo on 3v4l.org

Upvotes: 2

Obsidian Age
Obsidian Age

Reputation: 42354

You have an array.

Depending on what you want to do with it, you can either add the string as part of the first index:

$result = $array['boo']['far'][0] . $path;

Or push it to the next index of the array:

array_push($array['boo']['far'], $path);

Upvotes: 0

Related Questions