Search code examples
phpphp-8

substr returns an empty string when string is less than start characters long in PHP 8


The PHP docs for substr() says:

If string is less than start characters long, FALSE will be returned.

and gives the example

$rest = substr("abcdef", 4, -4);  // returns false

Interestingly this seems to be not true starting with PHP 8.0.0rc1 as in newer versions the function returns an empty string instead:

https://3v4l.org/RPU1s

Is this a bug in PHP or an undocumented change (or am I misunderstanding something)?


Solution

  • It seems like this was an intentional change as mentioned in https://php.watch/versions/8.0/substr-out-of-bounds

    and implemented here:

    https://github.com/php/php-src/pull/6182