PHP explode() Function


The explode() function is used to splits a string into an array. The "separator" parameter contains the original string to be split, so it cannot contain an empty string. It is a binary safe function.

Syntax
explode(separator,string,limit)
Parameter Description
separator (Required) Specify where to separate strings.
string (Required) String to split.
limit (Optional) Specifies the number of array elements to return. Can contain any integer value (zero, positive, or negative).
  • Zero - Returns an array containing one element
  • Positive(Greater than 0) - Returns an array containing the largest border element.
  • Negative(Less than 0) - Returns an array with the last-limit element removed.
String into an array
Example
<?php
$str = "Hi How are You?";
print_r (explode(" ",$str));
?>

Output

Array ( [0] => Hi [1] => How [2] => are [3] => You? )
Return the number of array elements using the limit parameter
Example
<?php
$str = 'Hi|Hello|Welcome|World';
// zero limit
print_r(explode('|',$str,0));
echo "<br>";
// positive limit
print_r(explode('|',$str,2));
echo "<br>";
// negative limit 
print_r(explode('|',$str,-2));
?>

Output

Array ( [0] => Hi|Hello|Welcome|World )
Array ( [0] => Hi [1] => Hello|Welcome|World )
Array ( [0] => Hi [1] => Hello )

Prev Next