What is explode() function in PHP
The explode() function is a binary-safe function in PHP, which used to break a string into an array. It breaks the string in various elements and returns them in a form array.
Syntax
explode(separator,string,limit)
Parameter
The explode() function takes three parameters one optional and two mandatory.
Parameter | Type | Description |
separator (mandatory) | string type | This parameter specifies the critical points where to break the string |
string (mandatory) | string | This parameter specifies the string which is to be split (explode) |
limit (optional) | integer |
This parameter specifies the number of elements in the array. This parameter can be +,- or 0.
|
Notes:
- The limit parameter was added in PHP version 4.0.1
- And the support for the negative limit was added in PHP 5.1.0
Return Value
The explode() function return an array created by splitting the string.
Examples of explode() function in PHP
Program 1) Basic Program
<?php
//PHP Program to illustrate the working of explode function
#Simple Program
//Array Variable
$cars = 'Maruti,Hyundai,Honda,Toyota,JEEP';
//Variable to store the data after explode
$explodeCars = explode(",", $cars);
//Printing the output
print_r($explodeCars);
?>
Output
Array
(
[0] => Maruti
[1] => Hyundai
[2] => Honda
[3] => Toyota
[4] => JEEP
)
Program 2) Advance Program
<?php
//PHP Program to illustrate the working of explode function
#Modrate level Program
//Array Variable
$cars = 'Maruti,Hyundai,Honda,Toyota,JEEP';
//With positive limit
echo "For Positive limit <br><br>";
//Variable to store the exploded value
$explodeCarsWithPositive = explode(",", $cars, 2);
//For Loop for the itteration to display the output
for($i=0; $i < sizeof($explodeCarsWithPositive); $i++){
echo $explodeCarsWithPositive[$i]."<br>";
}
//With negative limit
echo "<br><br>For Negative limit <br><br>";
//Variable to store the exploded value
$explodeCarsWithNegative = explode(",", $cars, -2);
//For Loop for the itteration to display the output
for($i=0; $i < sizeof($explodeCarsWithNegative); $i++){
echo $explodeCarsWithNegative[$i]."<br>";
}
?>
OUTPUT:
For Positive limit
Maruti
Hyundai, Honda, Toyota, JEEP
For Negative limit
Maruti
Hyundai
Honda