It has been three years ago this month that PHP 5.3.0 was released and quite a few legacy functions became deprecated. Since I have my hands on a serious amount of aging enterprise projects, I can without a doubt say that the most common deprecated function I see is split().

Replacing the split() function

One thing I focus on here is a providing a single, solid solution to common issues while cutting through a lot of misinformation and debate. By merely typing PHP’s deprecated error message into a search engine, you can instantly find many answers for this error and anything else you can think of.

The majority of developers immediately say to simply replace split() with explode(). For the purposes of updating code and, of course, writing new code, I “usually” agree with them.

Beware, though, because there are two ways that old code could be using split(): Either to split a string using an expression or to split a string using a delimiter (another string).

Solid Statement: Replace all instances of the split() function with explode() when you need to split by a simple string. Replace all instances of the split() function with preg_split() when you need to split by a regular expression.

Usage Stays the Same

The best thing about updating your code from split() is that the usage stays the same. You end up just changing the word “split” to “explode” or “preg_split” and the arguments and their order stay the same.

All three use the same argument setup. Only the regular expression forward slashes in preg_split make them any different. Check out the 3 examples below that all return the same array:

<?php
$str = "Solidly,Stated,has,great,tutorials";
 
$mysplit= split(",",$str,3);
print_r($mysplit);
 
$myexplode = explode(",",$str,3);
print_r($myexplode);
 
$mypregsplit = preg_split("/,/",$str,3);
print_r($mypregsplit);
?>
 
Array ( [0] => Solidly [1] => Stated [2] => has,great,tutorials )
Array ( [0] => Solidly [1] => Stated [2] => has,great,tutorials )
Array ( [0] => Solidly [1] => Stated [2] => has,great,tutorials )

Why not always use preg_split?

That’s a good question, since preg_split can do both what explode does and handle regular expressions too.

We need only glance at the PHP.net manual to see that “If you don’t require the power of regular expressions, it is faster to use explode(), which doesn’t incur the overhead of the regular expression engine.”

Bonus Info

The deprecated split() function has a opposite function join() that performs the reverse. The explode() function also has an opposite function implode().

The implode() and join() functions are aliases of one another. However, the explode() and split() functions are not. There is your fun tip for the day.