How to split a string into an array in PHP

The explode() function is an built-in function in PHP which is used to break or split a string into an array by a separator string like comma, hyphen, space etc. This function is binary-safe.

Syntax:

explode(separator,string,limit)

separator – This parameter is required. It specifies where to break the string.

string – This parameter is required. The string to split.

limit – This parameter is Optional.  It specify the number of array elements to return.

The Explode() function returns:

  • Greater than 0 – An array with a maximum of limit elements.
  • Less than 0 – An array except for the last -limit elements.
  • 0 – An array with one element.

Example:

<?php
$str = 'A good programmer looks both ways before crossing a one-way street.';
print_r(explode(" ",$str));
echo "<br>";
print_r(explode(" ",$str,5));
?>

Output:

Array ( [0] => A [1] => good [2] => programmer [3] => looks [4] => both [5] => ways [6] => before [7] => crossing [8] => a [9] => one-way [10] => street. )
Array ( [0] => A [1] => good [2] => programmer [3] => looks [4] => both ways before crossing a one-way street. )

Praveen Kumar

I am a fullstack web developer with a passion for SEO, creating stunning websites, and organic marketing. I am a perfectionist.

Post navigation