How to use explode in PHP 8

Description

String operations are one the most common operations in any program. One of the most important operations is explode. It allows you to split a string at the same substring across the entire string. A common use case is the separation of a URL into its constituents: /blog/hello['', 'blog', 'hello']

explode in PHP 8

explode(string $separator, string $string, int $limit = PHP_INT_MAX): array

The explode function in PHP 8 takes 2 mandatory parameters. The $separator parameter tells PHP which character combination should be used to divide the string. The $separator can not be empty or null. The $string parameters indicates the string that should be divided. This parameter may be empty or null. The $limit parameter tells PHP 8 how many elements the returned array should have. If there were more options to divide the $string, the last entry in the array will consist of the remaining string. If $limit is negative, all elements except the last $limit elements will be returned. Below we will look at all possible combinations to illustrate explode's behavior in PHP 8 in more detail.

Examples

$separator = '/';

$array = explode($separator, '/blog/hello');

foreach( $array as $key => $value ){
    echo $key."\t=>\t".$value."\n";
}


0	=>	
1	=>	blog
2	=>	hello

Here we are already touching on an edge case of the explode function. As you can see below, the explode function generated 3 entries as result. Since the orignal string /blog/hello started with a /, the explode function will return an additional zero length string at the beginning of the array. As you might have guessed, the same holds at the end of the string.

$separator = '/';

$array = explode($separator, '/);

foreach( $array as $key => $value ){
    echo $key."\t=>\t".$value."\n";
}


0	=>	
1	=>

As expected, explode splits the string into an array of two zero length strings because the $string parameter consists of only the $separator string.

In order to reverse the operation, you would use the sibling function implode in PHP 8.