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.
🍭 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 (  => one  => 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