0

The following works:

echo "test {$var}";

This does not work:

echo "test {$var['value']}";

Is there a way to get that to work, without having to break up the string?

3
  • the second one also should work, maybe there is another error like you don't have such key in array Commented May 27, 2021 at 15:30
  • 1
    It absolutely should work as you have done it. What PHP version are you using? 3v4l.org/h9gX0 Commented May 27, 2021 at 15:30
  • @nice_dev I do not know the reason, but the input code I used was $var['value'] = 'a val'; echo "test {$var['value']}"; Commented May 27, 2021 at 15:49

4 Answers 4

0

Maybe you need to remove $var from memory by unset($var) if you want use it again as an array not as a string.

$var = 'works';
echo "test {$var}";
//test works

unset($var);// if don't use this 
//Fatal error will be thrown TypeError: Cannot access offset of type string on string


$var['value'] = 'also works';
echo "test {$var['value']}";
//test also works
Sign up to request clarification or add additional context in comments.

Comments

0

If it is an Array you should specify the index of value

echo "test $var[0]";

Or

echo "test {$var['0']}";

Comments

0

You should be able to just do echo "test $var[value]". This example worked perfectly for me:

$arr1 = array(
        "foo" => "hello",
        "bar" => "world"
    );
echo "Test $arr1[foo]\n";

$arr2 = array("hello", "world");
echo "Test $arr2[1]\n";

// You can also use variables
$get1 = "foo";
$get2 = 1;

echo "Test $arr1[$get1]\n";
echo "Test $arr2[$get2]\n";

This ouputs:

Test hello
Test world
Test hello
Test world

1 Comment

Fatal error: Uncaught Error: Undefined constant "value" you need to wrap it by single-quotes!
0

just use:


"test".$var['value']." ."

or

echo <<<EOHTML
<td>{$var['value']}</td>
EOHTML;

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.