PHP explode() Function

What is PHP explode() Function?

If you want to split a string into an array, use PHP explode() function. You can use a part of the string as separator to split it and the function places each split part in each element in the returned array. Usually space, comma, slash, new line, tab etc. are used as separators.

You can remember the explode() function as “String to Array”.

Syntax:

explode(separator, string, limit)

Parameters:

The Function has 2 required parameters and 1 optional parameter-

separator (Required): Part of the string that the function will use to split the string. It could be one or multiple characters of the string. Even, it might not be a part of the string. Check example 1.

  • If the separator is an empty string, the function throws a ValueError. Check example 2.
  • If the separator is something that doesn’t exist in the string, the function can’t find anything to separate the string and it returns an array with the entire string as one element. Check example 3.
  • In addition to the previous example, If the separator doesn’t exist in the string and you use any negative number in the “limit” parameter, the function trimmed off the only array element and returns an empty array. Check example 3.

string (Required): The string on which the function performs the split operation.

limit (Optional): It sets the number of array element you want the function returns. It could be a positive or negative number.

  • If it is positive number, the function splits the string into “limit” number. If the separator can split the function more than “limit” times, then the last element contains the rest of the string. On the other hand, if the “limit” specifies the greater number than the maximum number the separator can split the string, the function splits the string the maximum times the separator can split. Check example 4.
  • If it is negative number, the function splits the string as usual but the last “limit” elements will be trimmed off. And, the remaining elements are returned as an array. Check example 5.
  • If it is zero, the function splits the string into one array element. Actually, it is not possible to split a string by a separator by zero or even one part. Check example 6.

Return Values:

Splitting the string by the separator, the function returns an array that contains elements set by the “limit” parameter.

Examples:

Example 1: Splitting a string with one-character separator and multi-character separator-

<pre>
<?php
$arr = explode(" ", "PHP Python Java");
print_r($arr);
echo "<br />";
$arr = explode("\n\n", "PHP Python Java\n\nMySQL PostgreSQL MongoDB");
print_r($arr);
echo "<br />";
?>
</pre>

Output:

Array
(
    [0] => PHP
    [1] => Python
    [2] => Java
)

Array
(
    [0] => PHP Python Java
    [1] => MySQL PostgreSQL MongoDB
)

Explanation:

Line 3: First explode() splits with one character long separator, the space ” “.

Line 6: Second explode() splits with a multi-character long separator, the space “\n\n”.

Example 2: Splitting a string with an empty separator-

<pre>
<?php
$arr = explode("", "PHP Python Java");
print_r($arr);
echo "<br />";*
?>
</pre>

Output:

Fatal error:  Uncaught ValueError: explode(): Argument #1 ($separator) cannot be empty in D:\xampp\htdocs\php\explode.php:15
Stack trace:
#0 D:\xampp\htdocs\php\explode() function.php(15): explode(”, ‘PHP Python Java’)
#1 {main}
  thrown in D:\xampp\htdocs\php\explode.php on line 15

Explanation:

As the explode() function tries to split with the empty separator “”, it produces a ValueError error.

Example 3: Splitting a string with a nonexistence character separator-

<pre>
<?php
$arr = explode("-", "PHP Python Java");
print_r($arr);
echo "<br />";
$arr = explode("-", "PHP Python Java", -1);
print_r($arr);
?>
</pre>

Output:

Array
(
    [0] => PHP Python Java
)
Array
( )

Explanation:

Line 3: The function is trying to split with dash (-) as separator but it doesn’t exist in the string, hence, it returns the whole string as it is in the returned array.

Line 6: When the function uses a nonexistence character separator, it returns the whole string as one array element. But, it removes that element when it uses “-1” as the 3rd parameter.

Example 4: Splitting a string with positive “limit” number-

<pre>
<?php
$arr = explode(" ", "PHP Python Java", 2);
print_r($arr);
echo "<br />";
$arr = explode(" ", "PHP Python Java", 4);
print_r($arr);
?>
</pre>

Output:

Array
(
    [0] => PHP
    [1] => Python Java
)
Array
(
    [0] => PHP
    [1] => Python
    [2] => Java
)

Explanation:

Line 3: As the limit parameter splits the function into 2 parts, the second split part contains the rest of the string.

Line 6: The limit parameter asks the function to split the string into 4 parts. But, the separator can’t split it more than 3 parts. So, the function splits the string 3 parts which is the maximum number.

Example 5: Splitting a string with negative “limit” number-

<pre>
<?php
$arr = explode(" ", "PHP Python Java", -1);
print_r($arr);
echo "<br />";
$arr = explode(" ", "PHP Python Java", -2);
print_r($arr);
echo "<br />";
$arr = explode(" ", "PHP Python Java", -3);
print_r($arr);
echo "<br />";
$arr = explode(" ", "PHP Python Java", -4);
print_r($arr);
?>
</pre>

Output:

Array
(
    [0] => PHP
    [1] => Python
)

Array
(
    [0] => PHP
)

Array
(
)
Array
(
)

Explanation:

Line 3: The limit -1 removes last element from the array.

Line 6: The limit -2 removes last two elements from the array.

Line 9: The limit -3 removes last three elements from the array.

Line 12: The limit -4 removes asks to remove last four elements from the array, but there are 3 elements in array. In this case, it just returns the empty array.

Example 6: Splitting a string with zero or one as “limit”-

<pre>
<?php
$arr = explode(" ", "PHP Python Java", 0);
print_r($arr);
echo "<br />";
$arr = explode(" ", "PHP Python Java", 1);
print_r($arr);
echo "<br />";
?>
</pre>

Output:

Array
(
    [0] => PHP Python Java
)

Array
(
    [0] => PHP Python Java
)

Explanation:

Line 3 & Line 6: As it is not possible to split a string into 0 or 1 part, the explode() function returns the exact string as one array element.

Example 7: Splitting data from a CSV file-

<pre>
<?php
$csv = "JavaScript, 65.36%, 1995
HTML, 58.08%, 1991
PHP, 20.87%, 1993";
$languages = explode("\n", $csv);
foreach ($languages as $language) {
    $data = explode(", ", $language);
    echo "Language: {$data[0]}, User %: {$data[1]}, Introduced on: {$data[2]}" . "<br />";
}
?>
</pre>

Output:

Language: JavaScript, User %: 65.36%, Introduced on: 1995
Language: HTML, User %: 58.08%, Introduced on: 1991

Language: PHP, User %: 20.87%, Introduced on: 1993

Example 8: Splitting domain name from email address-

<pre>
<?php
$email = "contact@schoolsofweb.com";
echo "Email: " . $email . "<br />";
$arr = explode("@", $email);
echo "Domain: " . $arr[1];
?>
</pre>

Output:

Email: contact@schoolsofweb.com
Domain: schoolsofweb.com

Explanation:

The function uses @ as a separator and get the domain name in the second element in the returned array.

Example 9: Splitting a string that contains binary data-

<pre>
<?php
$str = "PHP \x41 abc";
$arr = explode(" ", $str);
print_r($arr);
?>
</pre>

Output:

Array
(
    [0] => PHP
    [1] => A
    [2] => abc
)

Explanation:

\x41 is a hexadecimal of A. the function can operate on data and splits the string.

Example 10: Splitting a string with an incorrect separator-

<pre>
<?php
$email = "Ontario and Fontana and Oakland and Richmond";
$arr = explode("and", $email);
print_r($arr);
?>
</pre>

Output:

Array
(
    [0] => Ontario 
    [1] =>  Fontana 
    [2] =>  Oakl
    [3] =>  
    [4] =>  Richmond
)

Explanation:

You want to split the four cities using separator “and”. It does so. But, “Orland” itself contains the separator. So, the function also splits it too.

Practical Usages of explode() Function:

This function has lots of practical applications. Few of those includes-

  • The function is very useful when you need to separate values from CSV (comma separated values) files. Check example 7.
  • It is also used to extract information from HTML documents.
  • You can use this function to get domain name from email address, or to get part from a long URL or file path etc. Check example 8.
  • This function is used to split user inputs such as tags (php, html, css), user supplied list etc.

Notes on this explode() Function:

  • PHP explode() is a binary-safe function. That means can work correctly on a string that contains binary data. Check example 9.
  • If you don’t use the 3rd parameter “limit”, the function uses PHP_INT_MAX as Default. PHP_INT_MAX is one of the core PHP predefined constants which is the largest integer that PHP supports. Its value is 2147483647 in 32-bit system and 9223372036854775807 in the 64-bit system.
  • If a separator is located in the beginning or at the end of the string, the function will create an empty array element on that respective position.

Best practices of PHP explode() Function:

  • Choose the correct separator to get the expected result. For example, separator might be a part of a word that you overlook and hence you get wrong result. If you use “and” as the separator in the “Ontario and Fontana and Oakland and Richmond” string, you’ll get 4 array elements instead of expected 5. Because “and” is a part of “Oakland”. Check example 10.
  • If you work on a user supplied string, validate and sanitize it before applying. It will protect you from potential risk such as malicious code injection to database, etc.
  • Use trim() function if it is required to remove extra whitespaces and other unwanted characters when using explode() function else you may not get the desire result.
  • Carefully set the limit parameter to get the correct number of array element.
  • Beside explode() function there are more splitting functions in PHP. Find out the correct reason to use this function and comment it.

PHP Version Support:

PHP 4, PHP 5, PHP 7, PHP 8

Summary: PHP explode() Function

explode() is one of the most used built-in string functions in PHP and a very powerful tool and a key PHP functions for string manipulation. It helps you to split a string into smaller chunks so that you can further process the data.

Reference:

https://www.php.net/manual/en/function.explode.php