String interpolation & escaping in PHP

Now that we learned about concatenating strings, there’s yet another way to combine multiple variables together, and that’s using something called string interpolation. This can be useful when dealing with strings that need to be output similar to this $numPostsDisplay, where we are combining two values together with a space.

It can be a bit difficult to understand how this string will be formatted, since we have a space within one of the outputted values, and there are spaces on each side of the period.

Let’s surround this entire variable assignment within double quotes, remove the period, and remove the single quotes. Wow — pretty easy to understand how this string is supposed to be formatted now, right?

<?php
$title = 'My Blog';
$numPosts = 10;
$numPostsDisplay = "$numPosts posts";
?>
<h1><?= $title ?></h1>
<h2><?= $numPostsDisplay ?></h2>

This isn’t possible with single quotes, but when we use double quotes, this ability to interpolate, or evaluate a variable within a defined string. This can greatly simplify the cognitive load when dealing with strings that are to be outputted.

If we wanted to use special characters within this string, we can escape them from this quoted string by prefixing them with a backslash. For example, to output a double quote, we escape it with a slash, and then type the double quote. We can do this on both sides of the 10.

<?php
$title = 'My Blog';
$numPosts = 10;
$numPostsDisplay = "\\"$numPosts\\" posts";
?>
<h1><?= $title ?></h1>
<h2><?= $numPostsDisplay ?></h2>

Then when refreshing, we will see that both double quotes have been outputted.

Complete and Continue  
Extra lesson content locked
Enroll to access source code, comments & track progress.
Enroll for Free to Unlock