PHP Variable substitution in String

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//from  www . j  av  a2 s. 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.





















Home »
  PHP Tutorial »
    Data Types »




Array
Array Associative
Array Util
ArrayObject
Data Types
Date
Date Format
DateTime
Number
String
String Escape
String Filter
String HTML
String Type
Timezone