PHP explode() Function

Example

Splitting a string into an array:

<?php
$str = "Hello world. I love Shanghai!";
print_r (explode(" ", $str));
?>

Run Example

Definition and Usage

The explode() function splits a string into an array.

Note:"separator"Parameter cannot be an empty string.

Note:This function is binary safe.

Syntax

explode(separator,string,limit)
Parameter Description
separator Required. Specify where to split the string.
string Required. The string to be split.
limit

Optional. Specify the number of elements in the returned array.

Possible values:

  • Greater than 0 - Returns an array containing up to limit Elements
  • Less than 0 - Returns an array containing all elements except the last onelimit All elements except the first one
  • 0 - Returns an array containing one element

Technical Details

Return value: Array of returned strings
PHP Version: 4+
Update Log: Negative numbers were added in PHP 4.0.1. limit Parameters. Negative numbers were added in PHP 5.1.0. limit Support.

More Examples

Example 1

Using limit Parameters to return some array elements:

<?php
$str = 'one,two,three,four';
// Zero limit
print_r(explode(',', $str, 0));
// Positive limit
print_r(explode(',', $str, 2));
// Negative limit
print_r(explode(',', $str, -1));
?>

Run Example