Concatenating strings in PHP

You can join together one or many strings in PHP, and there are a couple of ways to do it.

As we learned in the last lesson, we can convert two strings together using a period, also known as the concatenation operator. For the sake of this lesson, and so we don’t start getting confused, let’s set the number of posts back to the 10 integer. Let’s also remove the calls to gettype() since we don’t need them anymore.

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

First, if we needed to display a string right alongside an integer, the easiest way to do this is outside of a PHP tag.

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

When we refresh, we’ll see “posts” displayed.

But sometimes you will want to be able to do this programmatically, so let’s also create a new variable that manages the display text of this number of posts. We’ll name it $numPostsDisplay. This will replace the value currently within the <h2> tag.

That means we’ll assign it the value of $numPosts. Then, we’ll concatenate “posts” to the end using a period. Remembering from the previous lesson, this period concatenation operator operator casts both of these values to a string if they are not already strings. So $numPosts will be casted as a 10 string.

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

Then we will update the contents of the <h2> tag to output this $numPostsDisplay variable.

We can refresh the page, and see our “10 posts” string.

There’s another way to join strings together, and that’s by using what’s called a combined operator.

If we ever wish to assign a value over multiple lines, this is when we will use this method.

For example, rather than using a period inline, let’s assign $numPostsDisplay to $numPosts. Then, we will break ' posts' to the next line, and again call $numPostsDisplay, but using a .=. This tells PHP to take the previous value of $numPostsDisplay and concatenate on the related string.

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

And we refresh, and the output is the same.

This is more of a procedural programming approach though, which means it runs through multiple lines using a top-down approach. This isn’t a very succinct way of writing code, so let’s back this out and opt for the inline concatenation method, as it’s much, much cleaner and easier to read.

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

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