Variable substitution

Variable substitution provides a convenient way to output variables embedded in string literals. When PHP parses double-quoted strings, variable names are identified when a $ character is found and the value of the variable is substituted. We have already used examples earlier in this chapter such as:

$cm = 127;
$inch = $cm / 2.54;
// prints "127 centimeters = 50 inches"
echo "$cm centimeters = $inch inches";

When the name of the variable is ambiguous, braces {} can delimit the name as shown in the following example:

$memory = 256;
// Fails: no variable called $memoryMbytes
$message = "My computer has $memoryMbytes of RAM";
// Works: Curly braces are used delimit variable name
$message = "My computer has {$memory}Mbytes of RAM";
// This also works
$message = "My computer has ${memory}Mbytes of RAM";

Braces are also used for more complex variables, such as multidimensional arrays and objects:

echo "Mars is {$planets['Mars']['dia']} times the diameter of the Earth";
echo "There are {$order->count} green bottles ...";

Example 2-4 shows how the multidimensional array $planets is assigned, and objects and the member access operator -> are discussed in Section 2.11.

Length of a string

The length property of a string is determined with the strlen( ) function, which returns the number of eight-bit characters in the subject string:

integer strlen(string subject)

Consider an example that prints 16:

print strlen("This is a String");  // prints 16

by BrainBellupdated