Variables, arrays and objects interpolation in PHP strings

  John Mwaniki /    Updated on 07 Jul 2024

In this article, we are going to cover what strings interpolation is and the different methods of interpolating variables, array values, and objects in PHP language with aid of multiple examples.

Variables and Strings

Variables in PHP

In computer programming, a variable is the symbolic name of a container (computer memory location) for storing information in a computer program and whose value can change during the program's execution depending on conditions or on information passed to the program.

A variable can store different types of data such as integer, float, double, char, string, boolean, array, object, etc.

In many programming languages, you have to define a data type when declaring (specifying its name and properties) a variable.

However, PHP has no command for declaring a variable. In PHP, a variable is created the moment you first assign a value to it. You can name your variable anything you want but in PHP it has to start with $ followed by the name of the variable.

To assign a value to a variable, you write a variable name followed by an equal sign "=" and then the value.

Example

$variable1 = "I love programming in PHP"; // Assigning a string value
$variable2 = 30; // Assigning an integer value
$variable2 = 72.5; // Updating the value of the variable
$variable3 = 92-37; // Assigning a value from arithmetic operation

In the scope of this article, we will only expound more on string data type (though we will cover interpolation for arrays and objects) as covered below.

Strings in PHP

A string is a data type made up of a sequence of characters, either as a variable or a literal constant.

It comprises a series of characters which can include alphabets, numeric figures, or special symbols and characters.

in most cases, the string content needs to be enclosed within quotes for it to be considered a string.

However, there are four different ways of specifying strings in PHP which include:

1. Single quoted

This method involves enclosing text within single quotes (').

<?php
$mystring = 'This is a string';
echo $mystring; // Output: This is a string

echo 'This is a string'; // Output: This is a string

 

2. Double quoted

This method involves enclosing text within double quotes (").

<?php
$mystring = "This is a string";
echo $mystring; // Output: This is a string

echo "This is a string"; // Output: This is a string

 

3. Heredoc Syntax

This method is used for creating multi-line strings. It uses the operator "<<<" followed by an identifier(any text), and then immediately followed by a newline. The string value follows, and then the same identifier is again used to mark the end of the string. The closing identifier must be alone in a newline followed by a semi-colon (;) and with no whitespace before or after it.

<?php
$mystring = <<<ANYTEXT
This is paragraph 1
This is paragraph 2
ANYTEXT; 

 

4. Nowdoc Syntax

This method is very similar to heredoc, only that its identifier is enclosed in single quotes.

<?php
$mystring = <<<'ANYTEXT'
This is paragraph 1
This is paragraph 2
'ANYTEXT'; 

 

Now that we have covered what a string is, and the different ways of specifying it in PHP, it is also important to note that you can join two strings into one.

Strings & variable concatenation

Concatenation is the operation of joining two or more strings to form one string.

In PHP, we use the dot operator (.) to concatenate strings.

Examples

<?php
$name = "John";
echo "My name is ".$name;
// Output: My name is John.

$string1 = 'I like ';
$string2 = 'programming ';
$string3 = 'in PHP';
$string4 = $string1.$string2.$string3;
echo $string4;
// Output: I like programming in PHP

$string = "My name";
$string .= " is ";
$string .= "John";
echo $string;
// Output: My name is John

You can as well insert a variable inside a string. You achieve this through concatenation or interpolation.

To do this through concatenation, simply break the string at the position you want the variable to appear and concatenate it with the variable being outside of the quotes, then with the other part of the string.

Example

<?php
$age = '36yrs';
echo 'Peter is '.$age.' old';
// Output: Peter is 36yrs old

Concatenation is the only way of inserting variables into single-quoted strings.

Interpolation in PHP strings

The term interpolation means the insertion of something of a different nature into something else.

Variable interpolation is the insertion of variables inside the string value. As opposed to the concatenation method covered above, interpolated variables are parsed and replaced with their values while the string gets processed.

In PHP, the variable interpolation only works with double-quoted and heredoc specified strings.

For single-quoted strings, use the concatenation method as that type of string cannot parse variables and special characters.

There are two methods/syntaxes of variable interpolation in PHP strings which include:

  1. Simple syntax
  2. Complex syntax

1. Simple syntax

As its name suggests, this most common and simplest method of interpolating. It provides a way to embed variables, array values, or an object property in a string.

Example 1: Interpolating a variable

<?php
$age = "36yrs";
echo "Peter is $age old";
// Output: Peter is 36yrs old

 

Example 2: Interpolating an object property

<?php
class People {

 public $name = 'John Doe';

}
$person = new People();
echo "My name is $person->name";
// Output: My name is John Doe

 

Example 2: Interpolating an array value

<?php
$person = array("name" => "John Doe", "age" => 30);

echo "My name is $person['name']";
// Output: Won't work... Gives error: unexpected ''

echo "My name is $person[name]";
// Output: My name is John Doe

Note: PHP's simple string interpolation doesn't recognize quoted array keys and cannot parse them. To do array interpolation in strings using the simple syntax, you must use unquoted associative array keys eg. $person[name].

All the above methods work the same way for strings specified by heredoc syntax.

Example

<?php
$person = array("name" => "John Doe", "age" => 30);
echo <<<EOD
My name is $person[name]
EOD; 
// Output: My name is John Doe

 

2. Complex syntax

This method does not obtain its name from being complex, but rather because it allows for the use of complex expressions.

This method involves surrounding the variable with curly braces {} within a string literal.

PHP understands anything after { followed by $ as a variable and treats it as such by parsing it and replacing it with its value.

This method is especially useful when embedding variables within the textual content as they (variables, array values, and PHP objects) appear the same way as they would outside the string. This helps to prevent possible ambiguity between textual content and variables.

This syntax will only be recognized when { is immediately followed by $. Having space between them won't work.

Example

<?php
$name = "John Doe";
echo "My name is { $name}";
//Output: My name is { John Doe}

$name = "John Doe";
echo "My name is {$name}";
//Output: My name is John Doe

The {} syntax only interpolates variables starting with a $ into a string. This syntax does not evaluate arbitrary PHP expressions.

Example

<?php
echo "My age is: {2021-1993}";
//Output: My age is: {2021-1993}

 

Interpolating an object property

<?php
class People {

 public $name = 'John Doe';

}
$person = new People();
echo "My name is {$person->name}";
// Output: My name is John Doe

 

Interpolating an array value

<?php
$person = array("name" => "John Doe", "age" => 30);

echo <<<EOD
My name is {$person['name']}
EOD; 
// Output: My name is John Doe

Note: Unlike earlier in simple syntax, here we have used quoted array key and it works perfectly. When using quoted array keys, it's more recommendable to use complex (curly brace) syntax.

If for some reason you would want to use unquoted array keys in complex interpolation syntax, then the array key should be defined as a constant. Else, it will still work but a PHP warning will be given.

Example: Complex interpolation with unquoted array keys

<?php
$person = array("name" => "John Doe", "age" => 30);

echo "My name is {$person[name]}";
// Output: My name is John Doe
/*
PHP Warning: Use of undefined constant name - assumed 'name' (this will throw an Error in a future version of PHP) in /home/.../public_html/...
*/

define("name","name");
echo "My name is {$person[name]}";
// Output: My name is John Doe

 

Conclusion

In this article, we have covered what variables are and how to use them in PHP, what strings are, and the different methods of specifying them in PHP programs.

We have also covered how to do concatenation of strings in PHP.

We then covered what strings interpolation is, the different interpolation syntaxes, and how to do interpolations with variables, array values, and PHP objects.