ONE NET WIKI Free and professional IT Wiki

Variable parsing in PHP

2018-09-01 ONE NET WIKI

PHP-Tutorials-Guides-and-More.png

There are two types of syntax to parse a variable in PHP: a simple one and a complex one.


Simple syntax

If a dollar sign ($) is encountered, the parser will greedily take as many tokens as possible to form a valid variable name. Enclose the variable name in curly braces to explicitly specify the end of the name.

$name = "joshua";
// Valid. Explicitly specify the end of the variable name by enclosing it in braces:
echo "He drank some juice made of ${name}s.";

Similarly, an array index or an object property can be parsed. With array indices, the closing square bracket (]) marks the end of the index. The same rules apply to object properties as to simple variables.


Complex (curly) syntax

Any scalar variable, array element or object property with a string representation can be included via this syntax. Simply write the expression the same way as it would appear outside the string, and then wrap it in { and }.

Since { can not be escaped, this syntax will only be recognised when the $ immediately follows the {.

Use {\$ to get a literal {$.

$great = 'fantastic';
// Won't work, outputs: This is { fantastic}
echo "This is { $great}";

// Works, outputs: This is fantastic
echo "This is {$great}";

// PHP first looks for a constant named foo; an error of level E_NOTICE (undefined constant) will be thrown.
echo "This is wrong: {$arr[foo][3]}"; 

// Works. When using multi-dimensional arrays, always use braces around arrays when inside of strings
echo "This works: {$arr['foo'][3]}";

// Works.
echo "This works: " . $arr['foo'][3];
Editor's Note: All the articles in this website are original. If reproduced, please indicate the source and link.
430
0
All Comments (0)
Expand to publish a comment

Web Development


Web Management


Web Marketing


Web Security