Recipe 1.8. Interpolating Functions and Expressions Within Strings


1.8.1. Problem

You want to include the results of executing a function or expression within a string.

1.8.2. Solution

Use the string concatenation operator (.) , as shown in Example 1-27, when the value you want to include can't be inside the string.

String concatenation

<?php print 'You have '.($_REQUEST['boys'] + $_REQUEST['girls']).' children.'; print "The word '$word' is ".strlen($word).' characters long.'; print 'You owe '.$amounts['payment'].' immediately'; print "My circle's diameter is ".$circle->getDiameter().' inches.'; ?>

1.8.3. Discussion

You can put variables, object properties, and array elements (if the subscript is unquoted) directly in double-quoted strings:

<?php print "I have $children children."; print "You owe $amounts[payment] immediately."; print "My circle's diameter is $circle->diameter inches."; ?>

Interpolation with double-quoted strings places some limitations on the syntax of what can be interpolated. In the previous example, $amounts['payment'] had to be written as $amounts[payment] so it would be interpolated properly. Use curly braces around more complicated expressions to interpolate them into a string. For example:

<?php print "I have less than {$children} children."; print "You owe {$amounts['payment']} immediately."; print "My circle's diameter is {$circle->getDiameter()} inches."; ?>

Direct interpolation or using string concatenation also works with heredocs. Interpolating with string concatenation in heredocs can look a little strange because the closing heredoc delimiter and the string concatenation operator have to be on separate lines:

<?php print <<< END Right now, the time is END . strftime('%c') . <<< END  but tomorrow it will be END . strftime('%c',time() + 86400); ?>

Also, if you're interpolating with heredocs, make sure to include appropriate spacing for the whole string to appear properly. In the previous example, Right now the time has to include a trailing space, and but tomorrow it will be has to include leading and trailing spaces.

1.8.4. See Also

For the syntax to interpolate variable variables (such as ${"amount_$i"}), see Recipe 5.4; documentation on the string concatenation operator at http://www.php.net/language.operators.string.




PHP Cookbook, 2nd Edition
PHP Cookbook: Solutions and Examples for PHP Programmers
ISBN: 0596101015
EAN: 2147483647
Year: 2006
Pages: 445

Similar book on Amazon

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