Interpolating Variables in Strings


You can display the values of variables like this:

 $apples = 1; echo "Number of apples: ", $apples, "."; 

However, there's a shortcut that you can use to make this easier. The values in variables can be interpolated if you put them into double-quoted (not single-quoted) strings, which means that their values are inserted directly into the string. This technique enables you to convert the example from the previous chunk:

 $apples = 1; echo "Number of apples: $apples."; 

This example prints out Number of apples: 1. You can see the complete previous example, which displays variable values after assignment, converted to use variable interpolation in Example 1-5, phpinterpolation.php.

Example 1-5. Expanding variables in strings
 <HTML>     <HEAD>         <TITLE>             Interpolating variables         </TITLE>     </HEAD>     <BODY>         <H1>             Interpolating variables         </H1>         <?php             echo "Setting number of apples to 1.<BR>";             $apples = 1;             echo "Number of apples: $apples <BR>";             echo "Adding 3 more apples.<BR>";             $apples = $apples + 3;             echo "Number of apples now: $apples <BR>";         ?>     </BODY> </HTML> 

The results of this example appear in Figure 1-9.

Figure 1-9. Interpolating variable values.


Interpolation gives you a quick way of displaying the contents of a variable, but there's an issue to watch here. For example, what if the variable $text held the text "news", and you wanted to put the word "newspaper" into the output? You might try this:

 <?php     $text = "news";     echo "Where's the $textpaper <BR>"; ?> 

But PHP isn't going to understand that because it looks like you're using a variable named $textpaper. Here's the error you get:

 PHP Notice:  Undefined variable:  textpaper in C:\php\t.php on line 4 

The correct way to handle this situation is to enclose the variable you're interpolating, $text, in curly braces, { and }, as in Example 1-6.

Example 1-6. Expanding variables in strings
 <HTML>     <HEAD>         <TITLE>             Interpolating variables         </TITLE>     </HEAD>     <BODY>         <H1>             Interpolating variables         </H1>         <?php             $text = "news";             echo "Where's the {$text}paper.";         ?>     </BODY> </HTML> 



    Spring Into PHP 5
    Spring Into PHP 5
    ISBN: 0131498622
    EAN: 2147483647
    Year: 2006
    Pages: 254

    flylib.com © 2008-2017.
    If you may any questions please contact us: flylib@qtcs.net