PHP: Complex Variables in Strings

If you are at all familiar with PHP you are probably aware that you can put variables inside double quotes. For example:

$x = 5;
echo "x is equal to $x";

The above code will output “x is equal to 5″. This method works fine with simple variables, but will fail with references to member variables of objects or arrays:

//will not work
echo "x is equal to $myObject->x";
//also won't work
echo "x is equal to $myArra['x']";

To avoid this problem, PHP allows you to use curly braces to seperate variables that need to be parsed:

//will work
echo "x is equal to {$myObject->x}";

This is also useful in situations where you want to output a variable in the middle of a word:

//will not work
$birthday = 16;
echo "My birthday is on the $birthdayth";
//will work
echo "My birthday is on the {$birthday}th";

Note that { cannot be escaped in a string. If { is followed by $ PHP will assume that you want to parse a variable. To get the literal {$ you must escape it like this:

echo "Curly brace followed by dollar sign: {\$";
//will output
//Curly brace followed by dollar sign: {$

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

 

2 thoughts on “PHP: Complex Variables in Strings

  1. I dislike using curly braces (it makes the code look fulgy). I find something like:
    echo ‘My birthday is on the ‘.$birthday.’th’;
    Is a lot faster and looks so much better.

    • I don’t care much for the syntax either. Personally I like to avoid quotes all together in cases where there is more than one line of output:

      < ?php
      $birthday = 16;
      $today = 14;
      ?>
      Today is the < ?php echo $today; ?>th
      My birthday < ?php echo $birthday; ?>th,
      which is in < ?php $birthday - $today; ?> days.
      //more code

      I’m not so sure that it being faster is worth considering. I mentioned this in my post about over optimization. The performance difference between parsing the string versus concatenating it almost always negligable. In most cases I just use whatever method I think looks best.