New Try managed PHP hosting on Amezmo for FREE with a $50 account credit. Create account →

How Does The Explode Function In PHP Work?

Amezmo on

The PHP explode function is probably one of the most used functions in all codebases. Explode splits a string into components, but how does explode know when to split?

PHP puts every character from the passed in string into a new string. When PHP finds the separator, this string goes into the result array. What is the separator? The separator is typically a single character as ,;|=.

PHP allows not only just single characters, but full strings too. Of course, most uses of explode use a single character. In this case, we searched GitHub for references to explode and found the majority of explode uses a single character for the separator.

explode (string $delimiter, string $string [int $limit = PHP_INT_MAX]) : array

What Is The Meaning Of Explode?

Different from other languages that provide developers with builtin methods to split a string, PHP is unique in their choice of naming. In JavaScript, Python, and C#, the method we use to split up strings is `split`

At the same time, even if PHP is an outlier in terms of naming, the explode function is similar to the other languages above. Like the other languages, PHP takes the separator as the first argument.

However, it’s worth mentioning that PHP doesn’t consider primitive types as objects, while the other languages mentioned here do. With that being, core PHP internals developer, Nikita Popov, makes efforts for PHP to have methods on primitive types.

Of course, explode makes sense from a semantic point of view, but it’s a bit verbose. Newcomers to the language may wonder why there isn’t a split function. Let’s look at the definition of explode from the dictionary.

With this in mind, explode means to break something into pieces. It’s poetic, in a sense.

Laravel, the most popular PHP framework, provides its own implementation of split, among other utility methods. The framework provides helper methods on strings, which helps us to write more expressive PHP code.

Seeing that the lack of methods on primitive objects in PHP, Laravel provides Fluent Strings. The framework provides a split method that takes a regular expression instead of a character.

use Illuminate\Support\Str;

$lines = Str::of('A line of text in a paragraph\The second line of text')->split('/\n/');

Let’s explode a string, or Let’s split a string? Which naming do you prefer, split or explode?

Don’t want to play the role of IT administrator for your next Laravel app? Amezmo is a managed Laravel hosting provider that gives you a hands-off solution to hosting and deploying.

Host and Deploy Your PHP Apps for Free
Sign up today and see if Amezmo is right for you.
Read more from PHP