PHP – Explode

by Hiroshi on June 23, 2008

in Explode, PHP Functions

The PHP function explode lets you take a string and blow it up into smaller pieces. For example, if you had a sentence you could ask explode to use the sentence’s spaces ” ” as dynamite and it would blow up the sentence into separate words, which would be stored in an array. The sentence “Hello, world, PHP is amazing language.” would look like this after explode got done with it:

1. Hello,
2. world,
3. PHP
4. is
5. amazing
6. language

PHP Explode Example

<?php
$Number = "888-111-2222";
 
$Pieces = explode("-", $Number);
// note "-"
// We are asking the script to break pieces from left and right side of -
// This thing determines that what is separating the parts of a whole thing
echo "Whole Number = $Number <br />";
echo "Piece 1 = $num[0]<br />";
echo "Piece 2 = $num[1]<br />";
echo "Piece 3 = $num[2]";
?>

Result

Whole Number = 888-111-2222
Piece 1 = 888
Piece 2 = 111
Piece 3 = 2222

Random – Another Example

<?php
$animals = "cat mouse dog horse snake";
$selected = explode(" ", $animals);
// In this case our breaking point is a space and not -
// in 23423*343*7897678 the breaking point can be *
echo "All = $animals <br />";
echo "Second = $selected[1]<br />";
echo "Fourth = $selected[3]<br />";
echo "First = $selected[0]";
?>

Result

All = cat mouse dog horse snake
Second = mouse
Fourth = horse
First = cat

Related Posts

Previous post:

Next post: