explode() String Function in PHP 8.4 With Example

The `explode()` string function in PHP 8.4 is used to split a string into an array based on a specified delimiter. It is commonly used for breaking up comma-separated values (CSV), spaces, or any custom separators into an array.

Syntax

<?php
explode(string $separator, string $string, int $limit = PHP_INT_MAX): array
?>

`$separator` – The delimiter to split the string.
`$string` – The input string to be split.
`$limit` – Defines the maximum number of elements in the array.

Example 1: Basic Usage

<?php
$string = "apple,banana,orange";
$array = explode(",", $string);
print_r($array);
?>

Output:-

Array ( [0] => apple [1] => banana [2] => orange )

Example 2: Using `limit` Parameter

If you provide a positive limit, the last element will contain the rest of the string.

<?php
$string = "one|two|three|four|five";
$array = explode("|", $string, 3);
print_r($array);
?>

Output:-

Array ( [0] => one [1] => two [2] => three|four|five )

If the limit is negative, the function will exclude the last `N` elements.

<?php
$array = explode("|", $string, -2);
print_r($array);
?>

Output:-

Array ( [0] => one [1] => two [2] => three )

Example 3: Splitting on Spaces

<?php
$string = "PHP 8.4 is fast and powerful";
$array = explode(" ", $string);
print_r($array);
?>

Output:-

Array ( [0] => PHP [1] => 8.4 [2] => is [3] => fast [4] => and [5] => powerful )

Example 4: Handling Empty Strings

<?php
$string = "hello,,world";
$array = explode(",", $string);
print_r($array);
?>

Output:-

Array ( [0] => hello [1] => [2] => world )

Here, the second element is an empty string because of the double comma.