PHP: Variables from an array inside echo?

What’s the proper syntax to echo out variables from an array?

For example, suppose I need something like echo "$the_array['inside']";


It seems to me that your question should be clarified: what exactly is the problem?

echo "$the_array['inside']"; will output the $the_array['inside']'s value: the variables between double-quotes are interpreted.

echo $the_array['inside']; will do the same thing; the double-quotes were not necessary.

echo '$the_array['inside']'; will output $the_array['inside'] literally: the variables between simpler-quotes are not interpreted.

If $the_array['inside'] comes from an input of a user you have to protect it.

Does it answer your question?

1 Like

I’ve not tried the statement but think there would be a syntax error.

echo '$the_array[\'inside\’]’;

You’re right, sorry, I wrote too quickly

1 Like

echo "{$the_array['inside']}";

$array = [
    "foo" => "bar",
    "bar" => "foo",
    "fi"   => "fi",
    "fo"  => "fum",

// Not in a string
echo $array['bar'];

echo "These are arrays in a string {$array['bar']} and {$array['foo']}";

echo "These are arrays in an escaped string" . $array['bar'] . "and" .  $array['foo'];

That’s what I needed was the {}. I need to echo some variables out along with some other html.

I was using

 echo "

Which was a syntax error.

Don’t use escaped double-quotes, use single-quotes instead.

Are you outputting JSON? If so, you’re better off using json_encode.

I would not quote the a variable or $array['key'] at all within echo. I also would not echo text in full quotes as php needs to evaluate everything between full quotes. Just use single quotes and use concatenation to tie strings and variables together. Just my 2 cents.

echo 'My text goes here ' . $the_array['inside'] . ' and more text goes here';

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.