Adding, Updating and Removing Elements

3.Adding, Updating and Removing Elements

M

In this chapter

We'll learn how to add items to an array ($a[] =, array_push(), array_unshift()), change them, remove them (unset(), array_pop(), array_shift(), array_splice()), and check what's inside — isset() and array_key_exists() for keys, in_array() and array_search() for values, == and === for whole arrays — and why removing an item leaves a gap.

14–16 min

The Problem in Real Life

Ann Lee calls: she has to cancel her 10:00 booking. Saturday's day is a list of four bookings, and Ann's is item 2. Mia removes it with unset($day[2]); and runs the day view, which prints the bookings with a for loop from 0 to count($day) - 1.

Three lines come out: 9:00, 9:30 and then a warning, "Undefined array key 2". The 11:00 booking, which was there a minute ago, isn't printed at all.

M

I removed one booking. Why did another one disappear with it?

Mia

Removing an Item vs. Closing the Gap

Adding at either end

New bookings go at the end of the day, but an urgent one might go at the start. PHP has a function for each end.

Removing leaves a gap

unset() removes an item and its key — the other keys don't move up.

Is it in there?

Is there a key for 10:00? Is Ann among today's customers? Keys and values are checked differently.

Adding, Updating and Removing Elements

Arrays change: bookings are added, moved and cancelled all day. This chapter covers the five things you do to an array's contents:

  • Adding: $a[] = ..., array_push() and array_unshift().
  • Updating: writing to a key that exists.
  • Removing: unset(), array_pop(), array_shift() and array_splice().
  • Checking keys: isset() and array_key_exists().
  • Checking values: in_array() and array_search().

Adding: $day[] = $booking; adds an item at the end with the next integer key (chapter 2), and $prices["Hot towel"] = 2.5; adds an item under a key you choose. array_push($day, $a, $b) adds several items at the end. array_unshift($day, $booking) adds an item at the start; it renumbers the integer keys, so the old item 0 becomes item 1.

Adding items
<?php
$day = ["9:00 Tom Hart", "9:30 Clare Lefèvre"];
$day[] = "11:00 Sam Ortiz"; // at the end
array_push($day, "11:30 Zoë Müller"); // also at the end
array_unshift($day, "8:30 Daniel Brooks"); // at the start: keys renumbered
print_r($day);
// Array
// (
// [0] => 8:30 Daniel Brooks
// [1] => 9:00 Tom Hart
// [2] => 9:30 Clare Lefèvre
// [3] => 11:00 Sam Ortiz
// [4] => 11:30 Zoë Müller
// )

Updating: writing to a key that already exists replaces its value: $day[1]["service"] = "Beard trim"; changes one field of the second booking. That works because you write through the array variable itself. Changing a copy, as the next chapter shows, doesn't change the array.

Removing with unset: unset($day[2]) removes the item with key 2, key and all. The other keys don't move: the day now has keys 0, 1 and 3. That's Mia's bug. count($day) is 3, so her for loop asked for keys 0, 1 and 2. Key 2 no longer exists (warning), and key 3 — the 11:00 booking — was never asked for. There are two fixes. Loop with foreach, which visits the keys that really exist, or close the gap with array_values($day), which returns the same values with new keys 0, 1, 2. Use foreach for lists, and reach for for only when you really need the numbers.

Mia's bug: unset() leaves a gap
<?php
$day = ["9:00 Tom Hart", "9:30 Clare Lefèvre", "10:00 Ann Lee", "11:00 Sam Ortiz"];
unset($day[2]); // Ann cancels
echo implode(", ", array_keys($day)), "\n"; // 0, 1, 3: a gap at 2
for ($i = 0; $i < count($day); $i++) { // count is 3: asks for 0, 1, 2
echo $day[$i], "\n";
}
// 0, 1, 3
// 9:00 Tom Hart
// 9:30 Clare Lefèvre
// Warning: Undefined array key 2
Two fixes: foreach, or array_values()
<?php
$day = ["9:00 Tom Hart", "9:30 Clare Lefèvre", "10:00 Ann Lee", "11:00 Sam Ortiz"];
unset($day[2]);
foreach ($day as $booking) { // visits the keys that exist
echo $booking, "\n";
}
$day = array_values($day); // new keys 0, 1, 2
echo $day[2], "\n"; // 11:00 Sam Ortiz
// 9:00 Tom Hart
// 9:30 Clare Lefèvre
// 11:00 Sam Ortiz
// 11:00 Sam Ortiz

Removing from the ends, and from the middle: array_pop($day) removes the last item and returns it, and array_shift($day) removes the first item, returns it and renumbers the integer keys. array_splice($day, 2, 1) removes 1 item at position 2, returns the removed items, and renumbers the list so there's no gap. It can also insert: array_splice($day, 1, 0, [$booking]) puts a booking at position 1 without removing anything. Like sort(), these functions change the array you pass them: they take it by reference (Act 03).

pop, shift and splice
<?php
$day = ["9:00", "9:30", "10:00", "10:30", "11:00"];
echo array_pop($day), "\n"; // 11:00: the last item, removed
echo array_shift($day), "\n"; // 9:00: the first item, removed
echo implode(" ", $day), "\n"; // 9:30 10:00 10:30
$removed = array_splice($day, 1, 1); // remove 1 item at position 1
echo implode(" ", $removed), " | ", implode(" ", $day), "\n"; // 10:00 | 9:30 10:30
array_splice($day, 1, 0, ["10:00"]); // insert at position 1, remove nothing
echo implode(" ", $day), "\n"; // 9:30 10:00 10:30

Checking keys: isset($a["key"]) is true when the key exists and its value isn't null. array_key_exists("key", $a) is true when the key exists, whatever its value. The difference matters for fields that can be null: a booking with "note" => null has the key, but isset() says false. Most of the time isset() is what you want, and it's the fastest. To read a key that may be missing, use ?? (Act 05): $booking["note"] ?? "no note".

isset() vs. array_key_exists()
<?php
$booking = ["time" => "9:30", "note" => null];
var_dump(isset($booking["time"])); // bool(true)
var_dump(isset($booking["note"])); // bool(false): the value is null
var_dump(array_key_exists("note", $booking)); // bool(true): the key is there
var_dump(isset($booking["barber"])); // bool(false): no key, and no warning
echo $booking["note"] ?? "no note", "\n"; // no note

Checking values: in_array($value, $array) asks "is this value anywhere in the array?" and returns true or false. array_search($value, $array) returns the key of the first match, or false. That's chapter 3 of Act 07 again: if the match is at key 0, if (array_search(...)) treats it as not found, so compare with !== false. And pass true as the third argument to both functions, to compare strictly with ===. Without it, in_array("abc", [0]) is false in PHP 8, but in_array("1e1", ["10"]) is true.

in_array() and array_search()
<?php
$customers = ["Ann Lee", "Tom Hart", "Clare Lefèvre"];
var_dump(in_array("Tom Hart", $customers, true)); // bool(true)
var_dump(array_search("Clare Lefèvre", $customers)); // int(2): the key
var_dump(array_search("Ann Lee", $customers)); // int(0): found at key 0!
var_dump(array_search("Sam Ortiz", $customers)); // bool(false): not found
var_dump(in_array("1e1", ["10"])); // bool(true): loose == (Act 07)
var_dump(in_array("1e1", ["10"], true)); // bool(false): strict ===
if (array_search("Ann Lee", $customers) !== false) {
echo "Ann is booked today\n"; // Ann is booked today
}

Comparing two arrays: to check whether two whole arrays are the same, use == or ===, just like with single values — but they mean something different here. $a == $b is true when both arrays have the same key => value pairs, in any order, with values compared loosely. $a === $b also needs the same order and the same types. So ["time" => "9:00", "barber" => 12] == ["barber" => 12, "time" => "9:00"] is true, but === is false. For lists, order is usually what you care about, so use ===. The table below sums up the chapter.

Table — Changing and checking an array
JobFunctionKeys afterwards
Add at the end$a[] = $x; array_push($a, $x)Next integer key
Add at the startarray_unshift($a, $x)Integer keys renumbered
Remove by keyunset($a[$key])A gap is left
Remove the last / firstarray_pop($a) / array_shift($a)array_shift() renumbers
Remove or insert at a positionarray_splice($a, $pos, $count, $new)Renumbered, no gap
Renumberarray_values($a)0, 1, 2 …
Key there and not null?isset($a[$key])Unchanged
Key there at all?array_key_exists($key, $a)Unchanged
Value there?in_array($x, $a, true)Unchanged
Where is the value?array_search($x, $a, true)Unchanged; returns a key or false
Same pairs, any order?$a == $bUnchanged
Same pairs, same order, same types?$a === $bUnchanged
Comparing two arrays: == and ===
<?php
$a = ["time" => "9:00", "barber" => 12];
$b = ["barber" => 12, "time" => "9:00"]; // same pairs, other order
$c = ["time" => "9:00", "barber" => "12"]; // "12" is a string here
var_dump($a == $b); // bool(true): same pairs
var_dump($a === $b); // bool(false): different order
var_dump($a == $c); // bool(true): 12 == "12"
var_dump($a === $c); // bool(false): different types
var_dump(["9:00", "9:30"] === ["9:00", "9:30"]); // bool(true): same list

Key Takeaway

$a[] = adds at the end; array_unshift() adds at the start. unset() removes an item but leaves a gap in the keys — so loop with foreach, or renumber with array_values(). array_pop() and array_shift() take items off the ends; array_splice() removes or inserts at a position and renumbers. isset() checks a key that isn't null, array_key_exists() any key; in_array() and array_search() check values — strictly with true, and array_search() with !== false.

Why This Matters

Bookings are added, changed and cancelled all day, so the day's array changes all day. A cancelled booking that takes the next one with it, or a "not found" that was really found at position 0, is the kind of bug that sends a customer to a barber who isn't expecting them.

The rule that removes most of these bugs is simple: loop with foreach, check with isset() or ??, and compare values strictly.

The day view loops with foreach, and cancelling Ann no longer hides Sam. Next, Olivia asks Mia to raise every price by 10% before launch. She writes a foreach over the services and multiplies each price by 1.1. She prints the prices afterwards — every one of them is unchanged. That's the next chapter: destructuring, spreading and references.