APR
Handy unknown feature in PHP function explode()
Posted by Lee under Programming
I accidentally came across a mighty handy feature in the PHP explode() function today whilst doing an update to Breeze CMS that I cannot see documented anywhere. It certainly saved me what would have been a full re-write or reconsideration of the function I was writing!
What I found was that when using it in the following example:
$content = "Blah blah ##bitname## some more blah and then ##bitname## a bit more";
$parts = explode('##', $content);
print_r($parts);
The results were
Array
(
[0] => Blah blah
[1] => bitname
[2] => some more blah and then
[3] => bitname
[4] => a bit more
)
Which is exactly what I expected, but when you have the deliminator (##) at the start of the string like below
$content = "##bitname## blah blah ##bitname## some more";
You get the following result:
Array
(
[0] =>
[1] => bitname
[2] => blah blah
[3] => bitname
[4] => some more
)
Whats so special? See the first empty value in the array? The explode function creates an empty first array value if the first characters are the deliminator you are using. I don’t know if this is an intended feature but it is perfect for us as we know that each ‘bit name’ is always going to be an odd number.

Well, this behaviour is quite obvious. Neither is it a bug, nor a feature.
The ### is used as delimiter by explode(), thus the empty array item.
Feature might not have been the best choice of word I agree - unexpected (by me) result would have been better! The more I do look at it from a programming perspective (whereby ‘##’ is just a deliminator and not really needing the second ## to ‘close’ as such) the more obvious it does become. It sure is handy though for what we needed to use it for!