- PHP explode() Function
- explode
- Parameters
- Return Values
- Changelog
- Examples
- Notes
- See Also
- User Contributed Notes 3 notes
- php explode
- Introduction to the PHP explode() function
- PHP explode() function examples
- 1) Simple the PHP explode() function example
- 2) Using the PHP explode() function with a positive $limit
- 3) Using the PHP explode() function with a negative $limit
- 4) A practical example of the PHP explode() function
- Summary
- PHP Explode – How to Split a String into an Array
- Syntax of the explode() Function
- Examples of implode()
- Conclusion
PHP explode() Function
explode() is a built in function in PHP used to split a string in different strings. The explode() function splits a string based on a string delimiter, i.e. it splits the string wherever the delimiter character occurs. This functions returns an array containing the strings formed by splitting the original string.
array explode(separator, OriginalString, NoOfElements)
Parameters : The explode function accepts three parameters of which two are compulsory and one is optional. All the three parameters are described below
- separator : This character specifies the critical points or points at which the string will split, i.e. whenever this character is found in the string it symbolizes end of one element of the array and start of another.
- OriginalString : The input string which is to be split in array.
- NoOfElements : This is optional. It is used to specify the number of elements of the array. This parameter can be any integer ( positive , negative or zero)
- Positive (N): When this parameter is passed with a positive value it means that the array will contain this number of elements. If the number of elements after separating with respect to the separator emerges to be greater than this value the first N-1 elements remain the same and the last element is the whole remaining string.
- Negative (N):If negative value is passed as parameter then the last N element of the array will be trimmed out and the remaining part of the array shall be returned as a single array.
- Zero : If this parameter is Zero then the array returned will have only one element i.e. the whole string.
Return Type: The return type of explode() function is array of strings.
Input : explode(" ","Geeks for Geeks") Output : Array ( [0] => Geeks [1] => for [2] => Geeks )
Below program illustrates the working of explode() in PHP:
explode
Returns an array of strings, each of which is a substring of string formed by splitting it on boundaries formed by the string separator .
Parameters
If limit is set and positive, the returned array will contain a maximum of limit elements with the last element containing the rest of string .
If the limit parameter is negative, all components except the last — limit are returned.
If the limit parameter is zero, then this is treated as 1.
Note:
Prior to PHP 8.0, implode() accepted its parameters in either order. explode() has never supported this: you must ensure that the separator argument comes before the string argument.
Return Values
Returns an array of string s created by splitting the string parameter on boundaries formed by the separator .
If separator is an empty string («»), explode() throws a ValueError . If separator contains a value that is not contained in string and a negative limit is used, then an empty array will be returned, otherwise an array containing string will be returned. If separator values appear at the start or end of string , said values will be added as an empty array value either in the first or last position of the returned array respectively.
Changelog
Version | Description |
---|---|
8.0.0 | explode() will now throw ValueError when separator parameter is given an empty string ( «» ). Previously, explode() returned false instead. |
Examples
Example #1 explode() examples
// Example 1
$pizza = «piece1 piece2 piece3 piece4 piece5 piece6» ;
$pieces = explode ( » » , $pizza );
echo $pieces [ 0 ]; // piece1
echo $pieces [ 1 ]; // piece2
?php
// Example 2
$data = «foo:*:1023:1000::/home/foo:/bin/sh» ;
list( $user , $pass , $uid , $gid , $gecos , $home , $shell ) = explode ( «:» , $data );
echo $user ; // foo
echo $pass ; // *
Example #2 explode() return examples
/*
A string that doesn’t contain the delimiter will simply
return a one-length array of the original string.
*/
$input1 = «hello» ;
$input2 = «hello,there» ;
$input3 = ‘,’ ;
var_dump ( explode ( ‘,’ , $input1 ) );
var_dump ( explode ( ‘,’ , $input2 ) );
var_dump ( explode ( ‘,’ , $input3 ) );
?php
The above example will output:
array(1) ( [0] => string(5) "hello" ) array(2) ( [0] => string(5) "hello" [1] => string(5) "there" ) array(2) ( [0] => string(0) "" [1] => string(0) "" )
Example #3 limit parameter examples
// positive limit
print_r ( explode ( ‘|’ , $str , 2 ));
// negative limit
print_r ( explode ( ‘|’ , $str , — 1 ));
?>
The above example will output:
Array ( [0] => one [1] => two|three|four ) Array ( [0] => one [1] => two [2] => three )
Notes
Note: This function is binary-safe.
See Also
- preg_split() — Split string by a regular expression
- str_split() — Convert a string to an array
- mb_split() — Split multibyte string using regular expression
- str_word_count() — Return information about words used in a string
- strtok() — Tokenize string
- implode() — Join array elements with a string
User Contributed Notes 3 notes
Note that an empty input string will still result in one element in the output array. This is something to remember when you are processing unknown input.
For example, maybe you are splitting part of a URI by forward slashes (like «articles/42/show» => [«articles», «42», «show»]). And maybe you expect that an empty URI will result in an empty array («» => []). Instead, it will contain one element, with an empty string:
$uri = » ;
$parts = explode ( ‘/’ , $uri );
var_dump ( $parts );
Be careful, while most non-alphanumeric data types as input strings return an array with an empty string when used with a valid separator, true returns an array with the string «1»!
var_dump(explode(‘,’, null)); //array(1) < [0]=>string(0) «» >
var_dump(explode(‘,’, false)); //array(1) < [0]=>string(0) «» >
var_dump(explode(‘,’, true)); //array(1) < [0]=>string(1) «1» >
If you want to directly take a specific value without having to store it in another variable, you can implement the following:
echo $status_only = explode(‘-‘, $status)[0];
php explode
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 ) : array
Code language: PHP (php)
The explode() function has the following parameters:
- $separator is the delimiter that the explode() function uses to split the $string.
- $string is the input string
- $limit specifies 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 ( , ):
$str = 'first_name,last_name,email,phone'; $headers = explode(',', $str); print_r($headers);
Code language: PHP (php)
array(4) < [0]=> string(10) "first_name" [1]=> string(9) "last_name" [2]=> string(5) "email" [3]=> string(5) "phone" >
Code language: PHP (php)
2) Using the PHP explode() function with a positive $limit
The following example uses the explode() function with the a positive $limit argument:
$str = 'first_name,last_name,email,phone'; $headers = explode(',', $str, 3); var_dump($headers);
Code language: PHP (php)
array(3) < [0]=> string(10) "first_name" [1]=> string(9) "last_name" [2]=> string(5) "email,phone" >
Code language: PHP (php)
As shown clearly in the output, the returned array contains three elements specified by the $limit argument. Also, the last element has the remaining string.
3) Using the PHP explode() function with a negative $limit
The following example uses the explode() function with the a negative $limit argument:
$str = 'first_name,last_name,email,phone'; $headers = explode(',', $str, -1); var_dump($headers);
Code language: PHP (php)
array(3) < [0]=> string(10) "first_name" [1]=> string(9) "last_name" [2]=> string(5) "email" >
Code language: PHP (php)
In this example, the explode() function returns an array of the string split by the comma ( , ). Also, it excludes the last element from the result array.
If you use -2 instead of – 1 for the $limit , the explode() function will remove the last 2 elements. For example:
$str = 'first_name,last_name,email,phone'; $headers = explode(',', $str, -1); var_dump($headers);
Code language: PHP (php)
array(2) < [0]=> string(10) "first_name" [1]=> string(9) "last_name" >
Code language: PHP (php)
4) A practical example of the PHP explode() function
The following str_after() function returns the remainder of a string after the first occurrence of a string:
function str_after($str, $search) < return $search === '' ? $str : array_reverse(explode($search, $str, 2))[0]; >
Code language: PHP (php)
- First, split the string into an array of two elements separated by the $search string.
- Second, reverse the result array and return the first element of the result array.
The following example uses the str_after() function to get the domain name part of an email:
// . echo str_after('john.doe@phptutorial.net', '@');
Code language: PHP (php)
phptutorial.net
Code language: PHP (php)
Summary
- Use the PHP explode() function to return an array of strings by splitting a string by a separator.
PHP Explode – How to Split a String into an Array
Kolade Chris
The PHP explode() function converts a string to an array. Each of the characters in the string is given an index that starts from 0. Like the built-in implode() function, the explode function does not modify the data (string).
Syntax of the explode() Function
The explode() function takes in three parameters:
The full syntax looks like this:
explode(separator, string, limit)
Unlike implode() which works even if the separator is not provided, the explode() function won’t work without the separator. So, just like the string split into an array, the separator is required. You can use the limit parameter to specify the number of arrays expected. It is optional.
Examples of implode()
Let’s say that I have the string «Hello World». If the string is passed into an explode() function, Hello takes an index of 0 in the array, and World takes an index of 1. Remember that arrays use zero-based indexing.
$str = "Hello world"; $newStr = explode(" ", $str); // We are printing an array, so we can use print_r() print_r($newStr);
If you specify a limit in the explode() function, the index(es) won’t be more than that number. For example, if you specify 2, all the strings would show, but the index won’t be more than 2.
$str = "CSS, HTML, PHP, Java, JavaScript"; $newStr = explode(" ", $str, 2); // We are printing an array, so we can use print_r() print_r($newStr);
You can see that the first element takes an index of 0 and the rest of the comma-separated elements take 1. The index is not more than the limit of 2 specified.
The explode() function looks at spaces in the string to split the string into an array. If you type two different words together, they are treated as one:
$str = "CSS HTMLPHP Java JavaScript"; $newStr = explode( " ", $str); // We are printing an array, so we can use print_r() print_r($newStr);
You can see that HTML and PHP got ptinted together because there was no space between them.
Conclusion
This article showed you how to use the explode() function in PHP.
Note that unlike implode() which works without the separator, the separator is very important in explode() . If you don’t specify a separator, explode() won’t work as expected.
$str = "CSS, HTML, PHP, Java, JavaScript"; $newStr = explode($str, 2); // We are printing an array, so we can use print_r() print_r($newStr);
And if you leave the separator as an empty string, you get an error: