PHP - explode() method

The function explode() splits a string into an array and returns an array of strings. The function has been available since PHP version 4+.
We can say that the method explode() breaks a string into multiple arrays using an delimiter and each array is a substring.

Notes:
Le  separator parameter cannot be an empty string.
The function explode() returns a Boolean type.

Example

$str = "Hello world!"; 
print_r (explode(" ",$str));
Runtime:

Array
(
[0] => Hello
[1] => world
[2] => !
)

Syntax

explode(separator,string,limit)

separator: required. Specify the delimiter separator to split the string.
string: required. The string to split.
limit: optional. Specify the number of arrays to return.
Possible values:
  • Greater than 0 - Returns an array with the maximum number of elements.
  • Less than 0: Returns an array except for the last elements.
  • 0 - Returns an array with a single element.

Example:

$str = 'orange, blue, green, red'; 

// limit 0
print_r(explode(',',$str,0));

// upper limit of 0
print_r(explode(',',$str,2));

// lower limit to 0
print_r(explode(',',$str,-1));
Runtime:

Array
(
[0] => orange, blue, green, red
)
Array
(
[0] => orange
[1] => blue, green, red
)
Array
(
[0] => orange
[1] => blue
[2] => green
)

References:
https://www.php.net/manual/fr/function.explode.php