Summary: in this tutorial, you’ll learn how to use the PHP explode() function to split a string by a separator into an array of strings.
Introduction to the PHP explode() function #
The PHP explode() function returns an array of strings by splitting a string by a separator. The following shows the syntax of the explode() function:
explode ( string $separator , string $string , int $limit = PHP_INT_MAX ) : arrayCode language: PHP (php)The explode() function has the following parameters:
$separatoris the delimiter that theexplode()function uses to split the $string.$stringis the input string$limitspecifies how the function will return the result array.
If the $limit is positive, the explode() function returns an array with $limit elements where the last element containing the rest of the string.
If the $limit is zero, explode() function interprets it as one. So the function returns an array with the original string.
If the $limit is negative, the explode() function splits the $string using the $separator. Also, it removes the last $limit elements from the result array.
Prior to PHP 8.0.0, the explode() function returns false if the $separator is an empty string. Starting from PHP 8.0.0, the explode() function throws a ValueError instead.
PHP explode() function examples #
Let’s take some examples of using the explode() function.
1) Simple the PHP explode() function example #
The following example uses the explode() function to split a string by a comma (,):
<?php
$str = 'first_name,last_name,email,phone';
$headers = explode(',', $str);
print_r($headers);Code language: PHP (php)Output:
array(4)
{
[0]=> string(10) "first_name"
[1]=> string(9) "last_name"
[2]=> string(5) "email"
[3]=> string(5) "phone"
}Code language: PHP (php)