The explode function in PHP

In PHP, you can split/explode the strings into “pieces” by specifying a delimiter. The split in PHP string may be required for different purposes, for example taking the phone number in dash format (123-4567-9876) and then splitting string to categorize country code and local codes etc.

See an example of PHP split

To split strings, the PHP provides a function called explode(). The PHP explode function takes a delimiter by which it will find and split the given string and return an array of split string. The complete syntax of the explode() function is given below.

PHP explode syntax 

The complete syntax of the explode PHP function is:

explode ( string $delimiter , string $string [, int $limit ] )

Where

  • The delimiter is the character to be used to find in a given string and split it.
  • $string is the variable or string that will split.
  • The $limit is an optional parameter, where you can specify or limit the string split.

An example of explode function

The following example uses only two parameters in the explode function. The explode function will split the whole string by a given parameter and assign it to an array.

We will use the echo statement to display array elements that are returned by explode function.

Experience this example online

Output

Phone N0 = 800-444-4444

First piece = 800

Second piece = 444

Third Chunk piece = 4444

As you can see, a phone number is broken by giving ‘-‘ in the explode function. The explode function returned the $phoneChunks array. Then we used the echo statement to display the created array elements.

An explode example with limit parameter

Following is a PHP split string example. The example shows how to use the limit parameter to return the given number of split strings in PHP explode function.

We simply added a number separated by ‘,’ in explode function to above example. See example below:

Experience this example online

The output will be:

Raw Phone Number = 800-444-4444
First piece = 800
Second piece = 444-4444

Notice: Undefined offset: 2 in …
Third piece =

As you can see, the explode function only broken the phone number in two pieces. As we tried displaying the third array element, it generated an error message.

Whereas you can see, the second piece contains the rest of phone number, after the string is broken into two.

 

Related: PHP implode