6

I know that in php I can put a variable name inside a quoted string when I use echo, but I apparently can't do this with a session variable. Can anyone explain why?

Here is the code, with the "offending" php commented out:

<?php
session_start();
$test = 100;
$_SESSION['test'] = 200;
?>
<html>
  <head>
    <title>Test</title>
  </head>
  <body>
  <p><?php echo($test."<br />");?></p>
  <p><?php echo("$test"."<br />");?></p>
  <p><?php echo($_SESSION['test']."<br />");?></p>
  <p><?php //echo("$_SESSION['test']"."<br />");?></p>
  </body>
</html>

And the output looks like this:

100

100

200

But if I uncomment the offending code line:

  <p><?php echo("$_SESSION['test']"."<br />");?></p>

I get no output and the following error:

Parse error: syntax error, unexpected T_ENCAPSED_AND_WHITESPACE, expecting T_STRING or T_VARIABLE or T_NUM_STRING in - on line 14

So I can go on my merry way knowing how to do it correctly (just keep the session variable outside of the double quotes), but I would really like to understand why this doesn't work for session variables.

Thanks!

hakre
  • 193,403
  • 52
  • 435
  • 836
doxguy
  • 185
  • 1
  • 3
  • 11
  • Please read the PHP manual about strings: http://php.net/strings, use `{$var}` instead. – hakre Nov 06 '11 at 16:34
  • Thanks... I had read that page, but re-read after your comment and realized there was a link I should have followed on that page to another that had the explanation. Sorry for asking something so trivial. :-) – doxguy Nov 06 '11 at 16:42

1 Answers1

18

Inside a double-quoted string you must enclose a complex variable (array or object property) in {}:

<p><?php echo("{$_SESSION['test']}"."<br />");?></p>

This isn't an issue with $_SESSION specifically, but any array accessed by quoted keys. Note, that you can include a numerically indexed array value with wrapping in {}, as in "echo $array[2] is two";

Michael Berkowski
  • 267,341
  • 46
  • 444
  • 390