PHP Explode
First, let me assure you that the explode function will not turn your computer into a flaming ball of fire. Instead, the explode function will split a specified string into smaller parts, or “substrings”.
The PHP explode function is simply the opposite of the implode function.
For example, we can create separate arrays for a list of colors:
In the above example, each color is separated by a semicolon (;). By using the explode function, we can separate each color into an array:
The above code tells us to take the variable $colors and separate its contents between semicolons.
This bit of code would create an array of strings starting with the number zero:
We can use another example to show how you can use the explode function in the code as separate variables:
$places = explode(“,”, $assets);
echo “Total Assets = $assets <br />”;
echo “Millions Place = $places[0]<br />”;
echo “Thousands Place = $places[1]<br />”;
echo “Hundreds Place = $places[2]“;
This bit of code would display:
Total Assets = 6,149,360
Millions Place = 6
Thousands Place = 149
Hundreds Place = 360
Notice how we told the explode function to seperate $assets into different pieces each time there was a comma (,).
Explode Limits
With the explode function, you also have the ability to set a limit on the number of parts that are created.
For example, if we were to explode a huge number into separate parts which are separated by a comma with no limit, we would use the following code:
$numberparts = explode(” “, $number);
for($i = 0; $i < count($numberparts); $i++){
echo “Part $i = $numberparts[$i] <br />”;
}
This bit of code would display:
Part 0 = 94
Part 1 = 300
Part 2 = 694
Part 3 = 723
Part 4 = 801
Part 5 = 336
Part 6 = 528
(Remember that the number will always begin with zero)
Notice that the explode function will separate the number into as many parts divided by commas as it needs to until it reaches the last comma in the number.
By setting a limit to the explode function, we can limit the number of parts that are created.
For example, if we don’t want the number to be divided into any more than four parts, we would use the following code:
$numberparts = explode(” “, $number, 4);
for($i = 0; $i < count($numberparts); $i++){
echo “Part $i = $numberparts[$i] <br />”;
}
Notice the limit of 4 in the above code. This bit of code would display:
Part 0 = 94
Part 1 = 300
Part 2 = 694
Part 3 = 723,801,336,528
The limited explosion will stop exploding the original variable once it reaches four parts, then on the fourth part it will display what’s left.




