php · level 2 · unit 3 · lesson 1
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
cuts a string into pieces.
explode is the opposite of implode. explode(",", "tea,milk,jam") cuts the string at every comma and gives back an array: ["tea", "milk", "jam"]. The separator goes first, and it is thrown away.
When you know how many pieces there are, unpack them into named variables in one line: [$name, $score] = explode(":", "Mia:12");. That is . The first piece lands in $name, the second in $score.
Every piece is a string, even "12". To it to a whole number, write (int) in front: (int) $score.
<?php
$line = "Mia:12:Leeds";
[$name, $score, $town] = explode(":", $line);
echo "$name from $town scored $score\n";
$score = (int) $score;
echo gettype($score) . "\n";
$toppings = explode(", ", "cheese, tomato, basil");
echo count($toppings) . " toppings, first is " . $toppings[0] . "\n"; Data often arrives as one line of text with commas between the parts, so explode is one of PHP's busiest functions.
guess first
Turn a date around. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
<?php
$date = "2026-10-30";
[$year, $month, $day] = explode("-", $date);
echo "$day/$month/$year\n";
echo $month + 1 . "\n";
your turn
Your turn. Unpack a pet record.
Type a pet's name, a kind of animal and an age, with a comma between each and no spaces, like Rex,dog,4. Then run it.
fix it
The podium will not unpack. Can you fix it?
- The error says
Undefined array key 1, soexplodemade only one piece. Why did it not cut? - Look at what sits between the names on line 2, then at the separator on line 3.
- The names are split by
;, not,. Change the separator to";", then press run.
nailed it
you can cut text into neat pieces. :D
explodecuts a string at every separator.[$a, $b] = ...unpacks the pieces into variables.- Pieces are strings, and
(int)casts them to numbers.
new words in your collection
- explode
- destructuring
- cast
This lesson isn’t saved. A free account remembers every lesson you finish.