Splitting with explode()
Learn to split a string into an array by a delimiter with explode().
Splitting with explode()
To split a string into an array, use explode(). It is called as explode($delimiter, $string); $delimiter is the separator, $string is the string to split. The result is an array.
Example: explode(',', 'apple,pear,banana') returns ['apple', 'pear', 'banana']. It is the first tool you reach for when you need to handle each piece of a string separately.
Bounded splitting
explode() takes a third argument: $limit. When a positive number is given, the string is split into at most that many pieces; the rest stays in the last piece.
Example: explode(',', 'a,b,c,d', 2) returns ['a', 'b,c,d']. It splits at the first comma and keeps the rest as a single piece. This is useful for cases like file paths where the first part is special and the rest is free-form.
When the delimiter is not found
explode() still returns an array even when the delimiter is not found. In that case the whole string is placed in the array as a single piece. So explode(',', 'single piece') returns ['single piece']; it does not error.
This matters when you loop over the result. You can check the length with count() to see whether the delimiter was present. If you pass an empty string, you get [''] (one empty piece).
Exercise Reformat the date as day.month.year
Assign "2025-01-15" to $date. Use explode() with the '-' delimiter to assign the parts to $parts. Then in a single echo join $parts[2], '.', $parts[1], '.' and $parts[0] with the . operator (day.month.year order).
Show example solution
First assign $date, then $parts = explode("-", $date);. Finally add echo $parts[2] . "." . $parts[1] . "." . $parts[0];
Example solution:
<?php
$date = "2025-01-15";
$parts = explode("-", $date);
echo $parts[2] . "." . $parts[1] . "." . $parts[0];
Test yourself
-
What does explode(',', 'a,b,c') return?
explode(',', 'a,b,c')- abc
- a-b-c
- ['a','b','c'] (array)
- It errors
Show answer
['a','b','c'] (array) — Correct. It splits at each comma and returns a three-element array.
-
Split the date
$date = '2025-01-15'; $parts = ____('-', $date); echo $parts[0];Show answer
$date = '2025-01-15'; $parts = explode('-', $date); echo $parts[0];