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.
🍭 Realised this little tasty nugget existed today.
— Tim MacDonald (@timacdonald87) February 7, 2021
explode()'s 3rd parameter allows you to limit the number of returned segments. The last segment then contains the remainder of the string as is without further splitting, even if it contains the separator you are exploding on. pic.twitter.com/Sxle711SDI
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
).
Like this article?
Buy me a coffee👋 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.