explode() negative third argument¶
<?php
$string = 'a,b,c,d,e';
print_r(explode(',', $string, 3));
print_r(explode(',', $string, 0));
print_r(explode(',', $string, -2));
The third argument of explode() is a hidden gem.
When passed as a positive integer, it limits the number of part in the returned array. When it reaches the limit, it saves everything else in the last returned string. It saves on memory and processing time, when there are many separators in a long string.
When passed 0, explode() does nothing. This is not too useful, but it makes sense.
When passed a negative number, explode() limits the number of returned parts to that number, starting from the end. It also means that the last returned strings do not contain the separator anymore, unlike when passing a positive integer.
See Also¶
exploding tricks [Try me]
PHP Features¶
Last updated: 16 July 2026