Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP7's substr() behavior on null/empty strings

Tags:

string

php

substr

I was reading the PHP manual for substr(), in which it states the following about the input string parameter:

string

The input string. Must be one character or longer.

But further down the page in the examples section, this was one of the examples:

// ...
echo "6) ".var_export(substr("", 0, 1), true).PHP_EOL;
// ...

This obviously contradicts the specification for the input string which was required to be one character or longer. The page stated the output of the above would be 6) ''.

Coming from a C/C++ background I'm very careful of UB, so I would like to know if passing a NULL or "" to substr() is legal?

like image 807
John Mark Gabriel Caguicla Avatar asked Feb 11 '26 21:02

John Mark Gabriel Caguicla


1 Answers

Usually, you should take the PHP manual statements litterally, in particular for well-established core language functionalities. Here is a demo, for what it's worth.

https://3v4l.org/8RKbG .

IMO, you should be fine with an empty string (current implementations are protected against and I don't see that changing anytime soon). There is certainly no harm done in getting empty strings out of the way before calling substr() either.

A null value, however, seems to trigger a warning under HHVM (and only there), which is interesting. But the relevance of this fact is completely up to you.

like image 114
Calimero Avatar answered Feb 14 '26 12:02

Calimero



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!