String and Array Operators

4.String and Array Operators

M

In this chapter

We'll learn PHP's string operators — the dot for joining text and .= for adding to it — and its array operators: + for combining arrays (and why it ignored Tom's new price), == and === for comparing arrays, and the ... spread for joining lists.

12–14 min

The Problem in Real Life

Two small jobs today. First, the confirmation message: "Thanks, Zoë! Your haircut is booked for 10:15. Total: £25.00" — built from four variables. Mia gets it working quickly with dots.

Second, prices. BookBay has a default price list for every shop, and Tom has his own — his haircut is now £28. Mia combines them with $defaultPrices + $tomsPrices. The result still says £25.

"Plus on arrays isn't adding," says Marcus. "And it's not merging either, not exactly. It has one rule, and once you know it, you'll know which side to put Tom on."

M

I added Tom's prices to the defaults. Why did his price disappear?

Mia

Adding Numbers vs. Combining Text and Lists

Building sentences

Messages are glued together from many values — PHP needs an operator for that.

Two price lists, one key

When both arrays have "haircut", which price wins?

Same items, different order

Are two arrays equal if they hold the same items in a different order?

String and Array Operators

Operators for text and lists: besides numbers, PHP has operators for the two things you'll handle most in a web app — strings (text) and arrays (lists and collections, Act 04 chapter 3). Strings get two operators; arrays get a handful:

  • Concatenation, written as a dot: joins two strings into one.
  • Concatenating assignment, .=: adds text to the end of a string variable.
  • Array union, written +: combines two arrays by key.
  • Array comparison: == and === (and !=, !==) for whole arrays.
  • Spread, written ...: unpacks one array's items into another.

Concatenation: the dot . joins strings: "Tom" . "'s" is "Tom's". This joining is called concatenation. Values that aren't strings are converted (Act 04, chapter 7): "Total: £" . 25 is "Total: £25". PHP never adds spaces for you — put them inside the quotes. For short messages, writing variables inside double quotes (Act 02, chapter 5) is often easier to read; the dot is better when you join function results or constants, which double quotes can't fill in. The code below builds the confirmation message both ways.

Building the confirmation message
<?php
$customer = "Zoë";
$service = "haircut";
$time = "10:15";
$pricePence = 2500;
// With dots:
echo "Thanks, " . $customer . "! Your " . $service . " is booked for " . $time . ".\n";
// With a function result, the dot is needed:
echo "Total: £" . number_format($pricePence / 100, 2) . "\n";
// Variables inside double quotes, for comparison:
echo "Thanks, $customer! Your $service is booked for $time.\n";

Output: Thanks, Zoë! Your haircut is booked for 10:15. — then Total: £25.00 — then the same first line again.

Adding to a string with .=: $message .= " See you soon!"; adds text to the end of $message — it's the compound assignment from chapter 1, for strings. It's handy for building longer text step by step, like an email body or a report, one line at a time.

Adding to a string with .=
<?php
$message = "Thanks, Zoë!";
$message .= " Your haircut is at 10:15.";
$message .= " See you soon!";
echo $message;

Output: Thanks, Zoë! Your haircut is at 10:15. See you soon!

Array union with +: for arrays, + doesn't add numbers. $a + $b gives every item of $a, then adds the items of $b whose keys aren't in $a yet. When both arrays have the same key, the left array wins and the right value is ignored. That was Mia's bug: in $defaultPrices + $tomsPrices, both have "haircut", so the default (2500) won. Put the array that should win on the left: $tomsPrices + $defaultPrices gives Tom's 2800 plus every default he didn't override. Think of + as "fill in the gaps from the right".

Mia's bug: + keeps the left value
<?php
$defaultPrices = ["haircut" => 2500, "beardTrim" => 1000];
$tomsPrices = ["haircut" => 2800];
print_r($defaultPrices + $tomsPrices); // haircut stays 2500 (wrong)
print_r($tomsPrices + $defaultPrices); // haircut 2800, beardTrim 1000 (right)

+ with lists — a trap: lists have keys too: 0, 1, 2 (Act 04). So ["9:00", "9:30"] + ["11:00", "11:30", "12:00"] doesn't give five slots — keys 0 and 1 already exist on the left, so only "12:00" (key 2) is added. To join lists, use the spread operator ... inside square brackets: [...$morning, ...$afternoon] unpacks both lists into a new one, in order. The built-in array_merge() does a similar job, but for named keys the right side wins — the opposite of +. Act 08 covers both in depth; the table below compares them.

Table — Combining arrays
WaySame named key in bothTwo lists
$a + $bLeft ($a) winsOnly keys missing from $a are added
array_merge($a, $b)Right ($b) winsAll items, renumbered
[...$a, ...$b]Right ($b) winsAll items, renumbered
Joining two lists: + vs. spread
<?php
$morning = ["9:00", "9:30"];
$afternoon = ["11:00", "11:30", "12:00"];
print_r($morning + $afternoon); // 9:00, 9:30, 12:00 — two slots lost!
print_r([...$morning, ...$afternoon]); // all five, in order

Comparing arrays: == is true when two arrays have the same key/value pairs — in any order, and with loose comparison of the values. === is stricter: same pairs, in the same order, with the same types. So ["a" => 1, "b" => 2] == ["b" => 2, "a" => 1] is true, but with === it's false. As always, prefer === unless you specifically mean "same contents, order doesn't matter".

Comparing arrays
<?php
$a = ["haircut" => 2500, "beardTrim" => 1000];
$b = ["beardTrim" => 1000, "haircut" => 2500]; // same pairs, other order
var_dump($a == $b); // bool(true)
var_dump($a === $b); // bool(false): order differs
var_dump([1, 2] == ["1", "2"]); // bool(true): values compared loosely
var_dump([1, 2] === ["1", "2"]); // bool(false): types differ

Key Takeaway

The dot joins strings (converting other values) and .= adds to the end of one. For arrays, + keeps every key from the left array and only adds new keys from the right — so put the winning array on the left, and never use + to join lists; use [...$a, ...$b]. Arrays compare with == (same pairs, any order) or === (same pairs, same order, same types).

Why This Matters

Almost everything BookBay sends to a customer — confirmations, reminders, receipts — is text glued together from values. And combining configuration (defaults plus a shop's own settings) is one of the most common jobs in any app. Knowing that + lets the left side win turns a silent wrong price into a deliberate choice.

The list trap matters too: losing two time slots because + matched keys 0 and 1 is exactly the kind of bug that's invisible until a customer can't book.

Tom's £28 shows up, and every slot is in the list. Then Marcus opens Act 01's php.ini settings and points at a line Mia copied without understanding: error_reporting = E_ALL & ~E_DEPRECATED. Right below it, in the freelancer's code, there's a line starting with @. "Two more kinds of operator," he says, "one you'll read sometimes, and one you should almost never write." That's the next chapter.