Amit Merchant

Amit Merchant

A blog on PHP, JavaScript, and more

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

February 10, 2021 ·

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 (and 8.1), 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-read 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.

👋 Hi there! I'm Amit. I write articles about all things web development. If you like what I write and want me to continue doing the same, I would like you buy me some coffees. I'd highly appreciate that. Cheers!

Comments?