PHP: explode() function explained

By Parth Patel on Sep 12, 2021

The PHP explode() function converts a string to an array by splitting the string by a given delimiter (separator).

Syntax:

explode( $delimiter, $string, $limit]

Parameters:

  1. delimiter: string or character at which string has to be separated (eg. space, comma, colon etc) [REQUIRED]
  2. string: string to be separated [REQUIRED]
  3. limit: It is an optional integer argument:
    1. if limit is set and positive, the string will be split into array with maximum $limit elements where last element will contain rest of the string
    2. if limit is negative, the return array will contain all elements except last
    3. if limit is zero, it will be considered as 1

Return Type: The explode() function will return an array of strings.

Prior to PHP 8.0, explode() function would return false when the separator/delimiter parameter was passed empty, but now, it will throw ValueError.

Example:

<?php
$csv = "John Doe, 29, Toronto";
$user = explode(', ',$csv);

print_r($user);
?>

Output:

array(3)
{
	[0]=> string(8) "John Doe"
	[1]=> string(2) "29"
	[2]=> string(7) "Toronto"
}