In this chapter
We'll learn how to split a string into pieces with explode() and str_split(), join pieces with implode(), and format text and numbers with sprintf(), printf(), number_format() and str_pad() — to turn "Haircut;Hot towel" and 27.5 into "haircut and hot towel, £27.50".
The Problem in Real Life
Olivia wants two changes to the reminder. A booking stores its services in one field, separated by semicolons, and the reminder prints that field as it is: "your Haircut;Hot towel". She wants "your haircut and hot towel".
Then the price. A haircut with a hot towel costs £27.50, but the reminder says "Total: £27.5". A plain haircut says "Total: £25".
£27.5 looks like a typo. Prices always have two decimals: £27.50, £25.00.
Olivia
Raw Values vs. Formatted Text
Splitting and joining
One field with semicolons has to become a list, and a list has to become a sentence.
Numbers that look right
27.5 has to show as £27.50, and 9 as 09. Printing a number as it is isn't enough.
Lining things up
Tom's printed day list needs columns that line up, whatever the length of each name.
Splitting, Joining and Formatting Strings
From raw values to a finished message: good text needs two more skills: taking a string apart, and giving values exactly the right shape. This chapter covers both:
- Splitting:
explode()andstr_split()turn one string into an array of pieces. - Joining:
implode()turns an array into one string. - Formatting:
sprintf(),printf(),number_format()andstr_pad()control how numbers and text look.
explode: explode($separator, $string) splits a string wherever the separator appears and gives back an array of the pieces. (You met arrays in Act 06; Act 08 covers them fully.) explode(";", "Haircut;Hot towel") gives ["Haircut", "Hot towel"]. A third argument limits the number of pieces, and the last piece then keeps the rest of the string: explode(" ", "15:00 Haircut and hot towel", 2) gives the time, and then everything after the first space. If the separator isn't in the string at all, you get an array with one item, the whole string.
<?php$stored = "Haircut;Hot towel";$services = explode(";", $stored); // ["Haircut", "Hot towel"]echo count($services), " services\n"; // 2 servicesecho $services[0], "\n"; // Haircut$line = "15:00 Haircut and hot towel";$pieces = explode(" ", $line, 2); // at most 2 piecesecho $pieces[0], " | ", $pieces[1], "\n";// 15:00 | Haircut and hot towelecho count(explode(";", "Haircut")), "\n"; // 1: no separator, so one piece
str_split: str_split($string, $length) cuts a string into pieces of a fixed length instead: str_split("900123", 3) gives ["900", "123"]. Like everything in chapters 3 and 4, it counts bytes. To look inside an array while you learn, print_r() prints its items in a readable way.
<?phpprint_r(str_split("900123", 3));// Array// (// [0] => 900// [1] => 123// )
implode: implode($separator, $array) is the opposite of explode(). It joins every item of an array into one string, with the separator between the items — never after the last one. implode(" and ", ["Haircut", "Hot towel"]) gives Haircut and Hot towel. It's the easiest way to avoid a comma at the end or a missing space.
<?php$services = explode(";", "Haircut;Hot towel");echo implode(" and ", $services), "\n"; // Haircut and Hot towelecho strtolower(implode(" and ", $services)), "\n"; // haircut and hot towelecho implode(", ", ["Haircut", "Beard trim", "Hot towel"]), "\n";// Haircut, Beard trim, Hot towel — no comma after the last item$digits = "07700900123";echo substr($digits, 0, 5), " ", implode(" ", str_split(substr($digits, 5), 3)), "\n";// 07700 900 123
sprintf: sprintf($format, ...$values) builds a string from a format string: a template with placeholders that start with %. Each placeholder takes the next value and gives it a shape. %s puts in a string, %d a whole number, and %.2f a number with exactly two decimals, rounded. So sprintf("Total: £%.2f", 27.5) gives Total: £27.50. Between the % and the letter you can add a width: %02d means "at least two digits, filled with zeros", so sprintf("%02d:%02d", 9, 0) gives 09:00. That's the pattern Act 06 used for slot times. %% prints a real percent sign, and %1$s takes the first value again; write that one in single quotes, or PHP reads $s as a variable. The table below lists the common placeholders.
| Placeholder | Means | Example and result |
|---|---|---|
| %s | A string | sprintf("Hi %s", "Clare") gives Hi Clare |
| %d | A whole number | sprintf("%d slots", 16) gives 16 slots |
| %.2f | A number with 2 decimals, rounded | sprintf("£%.2f", 27.5) gives £27.50 |
| %02d | At least 2 digits, filled with 0 | sprintf("%02d:%02d", 9, 0) gives 09:00 |
| %5d | At least 5 wide, padded on the left | sprintf("[%5d]", 42) gives [ 42] |
| %-6s | At least 6 wide, padded on the right | sprintf("[%-6s]", "Ben") gives [Ben ] |
| %% | A percent sign | sprintf("%d%% off", 10) gives 10% off |
| %1$s | The first value (again) | sprintf('%1$s, %1$s!', "Hi") gives Hi, Hi! |
<?php$services = "haircut and hot towel";$total = 27.5;$message = sprintf("Your %s. Total: £%.2f.", $services, $total);echo $message, "\n"; // Your haircut and hot towel. Total: £27.50.echo sprintf("£%.2f", 25), "\n"; // £25.00echo sprintf("£%.2f", 9.999), "\n"; // £10.00: roundedecho sprintf("%02d:%02d", 9, 0), "\n"; // 09:00echo sprintf("[%5d] [%-6s] [%6s]", 42, "Ben", "Ben"), "\n"; // [ 42] [Ben ] [ Ben]echo sprintf("%d%% off", 10), "\n"; // 10% offecho sprintf('%2$s: %1$s', "Haircut", "15:00"), "\n"; // 15:00: Haircut
printf: printf() works exactly like sprintf(), but it prints the result instead of giving it back, and returns the number of bytes it printed. Use sprintf() when you need the text in a variable — for a message you're going to send — and printf() to print straight away.
<?php$bytes = printf("%d slots left\n", 3); // prints the line...echo $bytes, "\n"; // ...and returns its length: 13// 3 slots left// 13
number_format: number_format($number, $decimals) formats a number for people to read: number_format(1234.5, 2) gives 1,234.50, with a comma between the thousands. Two more arguments change the decimal point and the thousands separator, for countries that write 1.234,50. Use it for amounts you show; use sprintf() when the number is part of a fixed pattern.
<?phpecho number_format(1234.5, 2), "\n"; // 1,234.50echo number_format(1234.5), "\n"; // 1,235: no decimals, roundedecho number_format(1234.5, 2, ",", "."), "\n"; // 1.234,50echo "£" . number_format(27.5, 2), "\n"; // £27.50
str_pad: str_pad($string, $length, $padding, $side) makes a string at least $length long by adding a padding character, by default spaces on the right. STR_PAD_LEFT pads on the left, which lines up numbers by their last digit. That's how Tom's printed day list gets straight columns. sprintf() can pad too: %-10s pads a string to 10 on the right. Both count bytes, so a name with an é ends up one space short. Chapter 6 shows the fix, mb_str_pad().
<?php$bookings = [["09:00", "Daniel Brooks", 25],["09:30", "Ann Lee", 27.5],["10:00", "Sam Ortiz", 10],];foreach ($bookings as $booking) {echo $booking[0], " ",str_pad($booking[1], 15, "."),str_pad(number_format($booking[2], 2), 8, " ", STR_PAD_LEFT), "\n";}// 09:00 Daniel Brooks.. 25.00// 09:30 Ann Lee........ 27.50// 10:00 Sam Ortiz...... 10.00
Key Takeaway
explode() splits a string into an array at a separator; implode() joins an array into a string, with the separator only between items. sprintf() fills a format string — %s for text, %d for whole numbers, %.2f for two decimals, %02d for zero-padding — and returns it; printf() prints it. number_format() adds thousands separators, and str_pad() pads text to a width.
Why This Matters
Customers judge a business by its messages. "£27.5" looks like a mistake and "Haircut;Hot towel" looks like a machine; "your haircut and hot towel, £27.50" looks like Tom wrote it. sprintf() and number_format() are how every price, time and total gets its proper shape.
And explode() and implode() are the bridge between text and lists. You'll use them all the time: to read a line from a file (Act 15), to list services, or to take a code apart.
The reminder now reads "your haircut and hot towel tomorrow at 15:00. Total: £27.50." Then, testing the customer lookup, Mia finds something worrying. She types Tom's number without the first zero, "7700900123", and the screen shows Tom's bookings anyway. Two different strings, and PHP says they're equal. That's the next chapter: comparing strings.
