×

php · level 2 · unit 3 · lesson 1

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. 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.