Get "PHP 8 in a Nuthshell" (Now comes with PHP 8.3)
Amit Merchant

Amit Merchant

A blog on PHP, JavaScript, and more

Limit the number of returned segments in PHP's explode()

PHP’s documentation is a goldmine of little but helpful things which is when explored can help improve your code. But this kind of thing tends to get overlooked easily.

One such thing that I came across recently through Tim MacDonald’s tweet is the ability of PHP’s explode() function to limit the number of segments returned by it based on the separator.

Essentially, there’s a third parameter in explode() where you can specify how many segments you’d want to be returned irrespective of the fact that there may be more segments than the specified.

Check the following example.

$str = 'one|two|three|four';

print_r(explode('|', $str, 2));

/*
Array
(
    [0] => one
    [1] => two|three|four
)
*/

As you can see, when you specify the third parameter, the returned array will contain a maximum of limit (in our example it’s 2) elements with the last element containing the rest of string (two|three|four).

Learn the fundamentals of PHP 8 (including 8.1, 8.2, and 8.3), the latest version of PHP, and how to use it today with my new book PHP 8 in a Nutshell. It's a no-fluff and easy-to-digest guide to the latest features and nitty-gritty details of PHP 8. So, if you're looking for a quick and easy way to PHP 8, this is the book for you.

Like this article? Consider leaving a

Tip

👋 Hi there! I'm Amit. I write articles about all things web development. You can become a sponsor on my blog to help me continue my writing journey and get your brand in front of thousands of eyes.

Comments?