PHP Variable substitution in String

In this chapter you will learn:

  1. What is PHP Variable substitution in String
  2. Example - PHP Variable substitution in String
  3. Example - Including More Complex Expressions within Strings

Description

In PHP we can write variable name into a long string and PHP knows how to replace the variable with its value.

Example

Here is a script showing assigning and outputting data.


<?php// j a va2s .  c o m
       $name = "java2s.com";
       print "Your name is $name\n";
       $name2 = $name;
       print 'Goodbye, $name2!\n';
?>

The code above generates the following result.

Example 2

Consider the following situation:


<?php
$myValue = "cat"; 
echo "My favorite animals are $myValues";   
?>

The code above generates the following result.

We confused PHP if $myValues is a variable name or it is a plural form of a variable.

To get around this problem using curly brackets, as follows:


<?php
$myValue = "cat"; 
echo "My favorite animals are {$myValue}s";   
?>

The code above generates the following result.

You can also place the opening curly bracket after the $ symbol, which has the same effect:


<?php
$myValue = "cat"; 
echo "My favorite animals are ${myValue}s";   
?>

The code above generates the following result.

We can use the curly brackets to distinguish the variable name from the rest of the string.

Curly bracket syntax can insert more complex variable values, such as array element values and object properties.

Just make sure the whole expression is surrounded by curly brackets:


<?php
$myArray["age"] = 34; 
echo "My age is {$myArray["age"]}"; // Displays "My age is 34"   
?>

The code above generates the following result.

or we can create the string by concatenating the values together:


<?php
$myArray["age"] = 34; 
echo "My age is " . $myArray["age"]; // Displays "My age is 34"    
?>

The code above generates the following result.

Next chapter...

What you will learn in the next chapter:

  1. How to access PHP string element
  2. Syntax to access character in a string
  3. Example - Access single character in a string
Home » PHP Tutorial » PHP String
PHP String
PHP Single vs double quotation string
PHP String Escape Sequences
PHP Variable substitution in String
PHP String Element