Heredoc, Nowdoc and Concatenation

2.Heredoc, Nowdoc and Concatenation

M

In this chapter

We'll learn how to join strings with the dot operator and .=, the PHP 8 change in how + and the dot work together, and how heredoc and nowdoc let you write long, multi-line text — like a whole reminder message — as one readable block.

11–13 min

The Problem in Real Life

Mia opens send-reminders.php, the script that sends tomorrow's reminders. The message is built in one long statement: pieces of text and variables, glued together with dots and spread over three lines.

Tom has forwarded his own test reminder. It reads: "Hi Tom, this is a reminder of your haircut at Tom's Barbershoptomorrow at 15:00." Mia checks every piece of the statement. Each one is spelled correctly.

M

Every piece is right. So where did the space go?

Mia

Glued Pieces vs. One Template

Glued together

The dot operator joins strings exactly as they are — it never adds a space for you.

Hard to see the result

With many pieces, you can't see the finished message until the code runs.

Long, multi-line text

Messages and emails have several lines. A heredoc lets you write them the way they'll look.

Heredoc, Nowdoc and Concatenation

Building longer text: a reminder is more than one variable in a sentence. It has several values, several lines, sometimes a whole paragraph. PHP gives you two tools for that:

  • Concatenation: joining strings with the dot operator ., and adding to the end of a string with .=.
  • Heredoc and nowdoc: writing a long, multi-line string as one block, the way it will look.

The dot operator: . joins two strings into one; this is called concatenation. "Tom's" . "Barbershop" gives Tom'sBarbershop. The dot adds nothing between the pieces, not even a space. That was the bug: one piece ended with $shop and the next one started with "tomorrow, and nobody had put a space at the end or the start. With many pieces, a missing space is very easy to overlook, because the whole sentence never appears in the code. Numbers are turned into strings when you join them: "Slot " . 3 gives Slot 3.

The missing space
<?php
$customer = "Tom";
$service = "haircut";
$shop = "Tom's Barbershop";
$time = "15:00";
$message = "Hi " . $customer . ", this is a reminder of your " . $service
. " at " . $shop
. "tomorrow at " . $time . ".";
echo $message, "\n";
// Hi Tom, this is a reminder of your haircut at Tom's Barbershoptomorrow at 15:00.

Adding to a string with .=: $message .= "more text"; adds text to the end of the string that's already in $message. It's short for $message = $message . "more text";, just like += from Act 05. It's the usual way to build text step by step, for example one line per slot inside a loop.

.= builds text step by step
<?php
$times = ["9:00", "9:30", "10:00"];
$list = "Free slots:\n";
foreach ($times as $number => $time) {
$list .= "Slot " . ($number + 1) . ": " . $time . "\n";
}
echo $list;
// Free slots:
// Slot 1: 9:00
// Slot 2: 9:30
// Slot 3: 10:00

The dot and + in PHP 8: in PHP 8, + and - are calculated before the dot. So "Total: " . 20 + 5 means "Total: " . (20 + 5) and gives Total: 25. In PHP 7 the dot went first, which gave "Total: 20" + 5, a warning and a wrong number. Brackets make your meaning clear in every version: "Total: " . ($price + $tip). And remember that two dots never add: "Total: " . 20 . 5 gives Total: 205.

The dot and + in PHP 8
<?php
$price = 20;
$tip = 5;
echo "Total: " . $price + $tip, "\n"; // Total: 25 (PHP 8: + goes first)
echo "Total: " . ($price + $tip), "\n"; // Total: 25 — clearer with brackets
echo "Total: " . $price . $tip, "\n"; // Total: 205 — two dots join, they don't add

Heredoc: a heredoc writes a long string as a block. It starts with <<< and a name you choose, like SMS or TEXT. The text follows on the next lines, as many as you like, and the block ends with the same name on a line of its own. A heredoc works like a double-quoted string: variables are replaced and escape sequences work. But you don't need to escape double quotes, and the message in your code looks exactly like the message the customer will get, so a missing space has nowhere to hide. Since PHP 7.3, the closing name may be indented. PHP then removes that much indentation from every line, so the block can line up with the code around it.

The fix: the reminder as a heredoc
<?php
$customer = "Tom";
$service = "haircut";
$shop = "Tom's Barbershop";
$booking = ["day" => "tomorrow", "time" => "15:00"];
$message = <<<SMS
Hi $customer, this is a reminder of your $service
at $shop {$booking['day']} at {$booking['time']}.
Reply "C" to cancel.
SMS;
echo $message, "\n";
// Hi Tom, this is a reminder of your haircut
// at Tom's Barbershop tomorrow at 15:00.
// Reply "C" to cancel.

Nowdoc: a nowdoc is the single-quoted version of a heredoc. Put the name in single quotes, <<<'SMS', and nothing inside is replaced: $name stays $name, and \n stays \n. Use it for fixed text that contains dollar signs or backslashes, like a piece of example code, or a template with placeholders that you fill in later.

A nowdoc keeps everything as written
<?php
$template = <<<'SMS'
Hi {name}, your {service} is at {time}.
Prices are shown in £, never in $.
SMS;
echo $template, "\n";
// str_replace() (chapter 3) fills in the placeholders
echo str_replace(["{name}", "{service}", "{time}"], ["Clare", "haircut", "15:00"], $template), "\n";
// Hi {name}, your {service} is at {time}.
// Prices are shown in £, never in $.
// Hi Clare, your haircut is at 15:00.
// Prices are shown in £, never in $.

When to use which: for a short sentence, use a double-quoted string with the variables in it. For many lines, use a heredoc. To build text in a loop, use .=. To put formatted numbers, like prices, into a template, use sprintf() (chapter 4). Long chains of dots are hard to read and easy to break, as Mia just found. The table below sums it up.

Table — Ways to build a string
WayExampleUse it for
Double quotes"Hi $name, see you at $time."A short sentence with a few values
Dot operator$greeting . " " . $nameJoining two or three pieces
.=$list .= "$time\n";Building text step by step, often in a loop
Heredoc<<<SMS ... SMS;Long or multi-line text with variables
Nowdoc<<<'SMS' ... SMS;Long text that must stay exactly as written
sprintf()sprintf("£%.2f", $price)Text with formatted numbers (chapter 4)

Key Takeaway

The dot operator joins strings exactly as they are — it adds no spaces — and .= appends to a string. In PHP 8, + and - are calculated before the dot, but brackets keep it clear. A heredoc (<<<SMS) is a multi-line, double-quoted block that looks like the finished text; a nowdoc (<<<'SMS') is the same without interpolation.

Why This Matters

Every message BookBay sends is built from pieces: a name, a service, a time. When the pieces are glued together with dots over several lines, the finished sentence only exists when the code runs — so a missing space or a missing word reaches the customer before anyone has seen it.

A heredoc puts the finished message in the code, word for word. Anyone can read it, Tom included, and spot a mistake before it's sent.

The reminder is now one heredoc, and Tom's test message reads properly. Then Mia notices something else in the script. Tom marks his best customers by starting the booking note with "VIP", and their reminder should get one extra line: "Your free coffee is waiting." Not one VIP customer got it. The check uses a function called strpos(). That's the next chapter: searching, cutting and cleaning strings.