0

I have this variable

$foo['title'] = 'Hello World';

I want to access this variable from a string.

$string = '$foo["title"]';

How can I display "Hello World" by my variable $string?

I searched an other topic, i found something similar, unfortunately it doesn't work.

$foo['title'] = "Hello, world!";
$bar = "foo['title']";
echo $$bar;
2

2 Answers 2

2

Actually I am not sure I understand you goal.

Do you want maybe this?

$foo['title'] = "Hello, world!";
$bar = "$foo[title]";
echo $bar;

The result:

Hello, world!

This is the same as this:

$bar = $foo['title'];

Or you would like to prepend/append something? Like this:

$bar = 'prepend something ' . $foo['title'] . ' append something';
Sign up to request clarification or add additional context in comments.

Comments

0

You need to split the argument to the array away from the variable name, and then enclose the variable name in curly braces. So:

// get array argument
$matches = array();
preg_match("/\['(?s)(.*)'\]/", $bar, $matches);
$array_arg = $matches[1];

// get variable name
$arr = explode("[", $string, 2);
$var_name = $arr[0];

// put it together
${$var_name}[$array_arg]

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.