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

Amit Merchant · 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).

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!