0

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?

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

3 Comments

I figured eval() was the only way to go. Thanks!
@ScottFoster not sure if you saw but I did just edit with an alternate way. Always good to avoid eval if you can.
i'll check that out.
0

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.