Variable Substitution

PHP allows you to define strings using three methods: single quotation marks, double quotation marks, or heredoc notation. Heredoc isn't discussed here because it's fairly rare compared to the other two methods, but single quotation marks and double quotation marks work identically, with one minor exceptionvariable substitution.

Consider the following code:

echo $age;

That is a particularly clumsy way to print a variable as part of a string. Fortunately, if you put a variable inside a string, PHP performs variable substitution, replacing the variable with its value. That means we can rewrite the code like so:

echo "You are $age";

The output is the same. The difference between single quotation marks and double quotation marks is that single-quoted strings do not have their variables substituted. Here's an example:

echo "You are $age"; echo 'You are $age';

The first echo prints "You are 25", but the second one prints "You are $age".

Was this article helpful?

0 0

Post a comment