In this chapter
We'll learn how to take part of an array without changing it (array_slice()), how array_splice() differs, how to cut a list into batches with array_chunk(), and how to group a flat list of bookings by barber — the shape every day view needs — plus a quick round-up of searching.
The Problem in Real Life
Olivia's three wishes: the homepage shows the next three free slots; the reminders go out in batches of 2, because the SMS service accepts only two messages per second; and the counter screen shows the day grouped by barber.
Mia starts with the homepage. She remembers array_splice() from chapter 3 and takes the first three free slots with it. The homepage looks right. But the booking page, which uses the same list a few lines later, now starts at 10:30 — the first three slots have vanished from it.
I only wanted to show three slots. Why did they disappear from the booking page?
Mia
Taking a Copy vs. Cutting the Original
slice or splice?
Two functions with almost the same name: one copies a part, the other cuts it out of the original.
Batches
Seven reminders, two per second: the list has to be cut into pieces of two.
Grouped, not flat
The bookings come as one flat list. The screen needs them per barber: one list inside another.
Searching, Slicing, Chunking and Grouping
Taking a list apart: after sorting, the next jobs are usually "show part of it", "process it in pieces" and "split it into groups". This chapter covers:
- Slicing:
array_slice()copies a part;array_splice()cuts a part out. - Chunking:
array_chunk()cuts a list into batches of the same size. - Grouping: one
foreachthat turns a flat list into a list per barber. - Searching: a round-up of the ways to find an item.
array_slice copies: array_slice($slots, 0, 3) returns a new array with 3 items starting at position 0, and leaves $slots exactly as it was. Positions count from 0, a negative offset counts from the end (array_slice($slots, -2) gives the last two), and leaving out the length goes to the end. It renumbers integer keys unless you pass true as the fourth argument, $preserveKeys.
<?php$free = ["9:00", "9:30", "10:00", "10:30", "11:00"];echo implode(" ", array_slice($free, -2)), "\n"; // 10:30 11:00: the last twoecho implode(" ", array_slice($free, 1, 2)), "\n"; // 9:30 10:00print_r(array_slice($free, 3, 2, true)); // keep the original keys// Array// (// [3] => 10:30// [4] => 11:00// )
array_splice cuts: array_splice() (chapter 3) also returns those items, but it removes them from the original, because it takes the array by reference. That was Mia's bug: the homepage got its three slots, and the booking page lost them. The names are one letter apart, so here's a way to remember: splice is for inserting and removing; slice only looks. When you only want to show part of a list, use array_slice(). This "does it change my array?" question comes up with every array function, so the first table below collects the answers for this whole Act.
| Function | Changes the original? | Returns |
|---|---|---|
| sort(), rsort(), asort(), ksort(), usort() … | Yes | true |
| shuffle(), natsort() | Yes | true |
| array_push(), array_unshift() | Yes | The new number of items |
| array_pop(), array_shift() | Yes | The removed item |
| array_splice() | Yes | The removed items |
| array_walk() | Yes, through a reference | true |
| unset($a[$k]) | Yes | Nothing |
| array_slice(), array_reverse(), array_values() | No | A new array |
| array_filter(), array_map(), array_unique() | No | A new array |
| array_merge(), array_replace(), + | No | A new array |
| array_column(), array_diff(), array_chunk() | No | A new array |
<?php$free = ["9:00", "9:30", "10:00", "10:30", "11:00"];$homepage = array_splice($free, 0, 3); // takes 3 items OUT of $freeecho "Homepage: ", implode(" ", $homepage), "\n"; // Homepage: 9:00 9:30 10:00echo "Booking page: ", implode(" ", $free), "\n"; // Booking page: 10:30 11:00$free = ["9:00", "9:30", "10:00", "10:30", "11:00"];$homepage = array_slice($free, 0, 3); // a copy of 3 itemsecho "Homepage: ", implode(" ", $homepage), "\n"; // Homepage: 9:00 9:30 10:00echo "Booking page: ", implode(" ", $free), "\n"; // Booking page: 9:00 9:30 10:00 10:30 11:00
array_chunk: array_chunk($reminders, 2) cuts a list into a list of smaller lists, each with 2 items; the last one may be shorter. Loop over the chunks to send one batch at a time. true as the third argument keeps the original keys inside each chunk. The same idea pages long lists: 10 bookings per page is array_chunk($bookings, 10)[$page - 1].
<?php$phones = ["+447700900123", "+447700900456", "+447700900789", "+447700900321", "+447700900654"];foreach (array_chunk($phones, 2) as $number => $batch) {echo "Batch ", $number + 1, ": ", implode(", ", $batch), "\n";}// Batch 1: +447700900123, +447700900456// Batch 2: +447700900789, +447700900321// Batch 3: +447700900654
Grouping: PHP has no array_group_by() function — you write it as a foreach in two lines. For every booking, add it to the list under its barber's key: $byBarber[$booking["barber"]][] = $booking;. PHP creates $byBarber[12] the first time it's needed and then appends to it. The result is an array keyed by barber ID, each value a list of that barber's bookings. Sort the bookings first (chapter 8) and every group is already in time order, because the groups keep the order the items arrived in. Then ksort($byBarber) puts the barbers in ID order. The diagram below shows the whole pipeline from a raw list to the counter screen — it's exactly what the checkpoint asks you to build.
From a flat list of bookings to a day view
$bookings
a flat list, in the order the bookings were made
array_filter()
keep the confirmed bookings (keys keep their gaps)
usort() with strnatcmp()
time order, not text order; keys renumbered
$day[$b["barber"]][] = $b
one list per barber, already in time order
ksort($day)
barbers in ID order: ready to print
<?php$day = [["barber" => 15, "time" => "9:30", "customer" => "Daniel Brooks"],["barber" => 12, "time" => "9:00", "customer" => "Tom Hart"],["barber" => 12, "time" => "10:00", "customer" => "Clare Lefèvre"],["barber" => 15, "time" => "10:00", "customer" => "Sam Ortiz"],];$names = [12 => "Ben", 15 => "Leo"];usort($day, fn($a, $b) => strnatcmp($a["time"], $b["time"])); // sort first$byBarber = [];foreach ($day as $booking) {$byBarber[$booking["barber"]][] = $booking; // creates the group the first time}ksort($byBarber); // barbers in ID orderforeach ($byBarber as $id => $bookings) {echo $names[$id], ": ", implode(", ", array_column($bookings, "time")), "\n";}// Ben: 9:00, 10:00// Leo: 9:30, 10:00
Searching, a round-up: "is it there?" is in_array() for a value and isset() for a key. "Where is it?" is array_search(), which returns the key or false (chapter 3). "Which record has this field?" is array_column() with a key field followed by isset() (chapter 7), or, since PHP 8.4, array_find() — the next chapter. The table below lists this chapter's tools.
| Job | Code | Changes the original? |
|---|---|---|
| The first 3 items | array_slice($a, 0, 3) | No |
| The last 2 items | array_slice($a, -2) | No |
| Cut 3 items out | array_splice($a, 0, 3) | Yes |
| Batches of 2 | array_chunk($a, 2) | No |
| Group by a field | $groups[$item["barber"]][] = $item; | No (builds a new array) |
| Find a value's key | array_search($x, $a, true) | No |
Key Takeaway
array_slice() copies part of an array and leaves the original alone; array_splice() cuts the part out of the original. array_chunk() splits a list into batches of a fixed size. To group a flat list, loop once and append each item under its group's key: $groups[$item["barber"]][] = $item; — sort first, and every group is already in order.
Why This Matters
"Show the first few", "send in batches" and "group by" are on almost every screen of a booking system. Getting slice and splice wrong changes data that other parts of the page rely on, and the bug shows up somewhere else entirely — the hardest kind to track down.
The grouping loop is worth knowing by heart. Bookings per barber, per day, per customer: it's always the same two lines, and the next course's database results get grouped the same way.
The homepage shows three slots without taking them away, the reminders go out two at a time, and the counter screen is grouped by barber. To highlight each barber's first booking of the day, Mia writes $bookings[0]. For Leo, it highlights the wrong customer. That's the next chapter: PHP's newest array helpers.
