Example of explode()
There are two things to remember here:
- The
explode()
function returns an array, where each element is a “piece” from the explosion. None of those elements will contain the explosion string itself. So if I explode on the colon character by writingexplode(":", "here:are:four:words");
, that will return an array of the four words themselves without any colons. - If you want a particular element of an array, just access it using something like this:
$the_third_element_of_array_name = $array_name[2]
. The bracket syntax refers to a particular element in the array, so when you store it in a variable, it’s stored as a plain ol’ scalar variable, not an array.
1234567891011// store a plain old sentence in $sentence
$sentence
=
"First half of the sentence, second half of the sentence."
;
// explode $sentence into pieces wherever a comma appears, and store the (two) pieces that result as an array called $exploded_sentence
$exploded_sentence
=
explode
(
", "
,
$sentence
);
// I just want the second piece of the explosion, so I'll access the second element of the array using $exploded_sentence[1] (remember, the first piece can be accessed with $exploded_sentence[0])
$second_half
=
$exploded_sentence
[1];
// $second_half is a plain ol' scalar variable (not an array), so we can run IT through explode(). Let's do so by exploding on the space character: this will return as many pieces as there are words in the sentence
$second_half_exploded
=
explode
(
" "
,
$second_half
);
// $second_half_exploded is of course an array, so if we want the first word, we just access it at $second_half_exploded[0]
$first_word_second_half
=
$second_half_exploded
[0];
echo
$first_word_second_half
;