String Functions

PHP explode() Function

Topic: PHP String ReferencePrev|Next


The explode() function splits a string into an array by a separator string like space, comma, etc.

The following table summarizes the technical details of this function.

Return Value: Returns an array of strings.
Version: PHP 4+


The basic syntax of the explode() function is given with:

explode(separator, string, limit);

The following example shows the explode() function in action.

// Sample string
$str = "The birds are flying in the sky.";

// Split string by space and print
print_r(explode(" ", $str));


The explode() function accepts the following parameters.

Parameter Description
separator Required. Specifies where to split the string.
string Required. Specifies the string to be splitted.

Optional. Specifies the number of array elements to return. Possible values are:

  • If limit is set to a value greater than 0, the returned array will contain a maximum of limit elements with the last element containing the rest of string.
  • If limit is set to a negative value, all elements except the last -limit are returned.
  • If limit is set to 0, then this is treated as 1.

More Examples

Here're some more examples showing how explode() function actually works:

The following example shows how the limit parameter basically works.

// Sample string
$str = "One, Two, Three, Four, Five";

// Positive limit
print_r(explode(", ", $str, 3));

// Negative limit
print_r(explode(", ", $str, -1));

// Zero limit
print_r(explode(", ", $str, 0));

If a string does not contain the specified separator then this function will simply return a one-length array of the original string, as demonstrated in the following example:

// Sample string
$str = "Hello World!";

// Split string using non-existent separator
print_r(explode("|", $str));
Bootstrap UI Design Templates