Edit report at http://bugs.php.net/bug.php?id=52628&edit=1

 ID:                 52628
 Updated by:         ka...@php.net
 Reported by:        david at grudl dot com
 Summary:            substr() returns false for empty string
 Status:             Closed
 Type:               Feature/Change Request
 Package:            Strings related
 PHP Version:        Irrelevant
 Assigned To:        kalle
-Block user comment: N
+Block user comment: Y

 New Comment:

Then check the return value of substr():



if(($string = substr($old_string, 0, 5)) === false) {

        /* error */

}



There is a million ways to over come this problem, simply check the
string first before trying to substring it


Previous Comments:
------------------------------------------------------------------------
[2010-08-17 22:22:31] david at grudl dot com

Example: I have string $s and want to short it to 5 characters:



$res = substr($s, 0, 5);



Question: is $res string of boolean?

------------------------------------------------------------------------
[2010-08-17 22:19:54] ka...@php.net

I don't think it makes any sense to pass an empty string directly to
substr and make it behave weirdly. Just wrap it inside an if statement
to check if the string is empty if you are using userdata.



In either case, calling sub string on an empty string would return
nothing, simply casting it to a string makes it empty:

$string = (string) substr('', 0, 2);

------------------------------------------------------------------------
[2010-08-17 18:22:33] david at grudl dot com

Description:
------------
substr() should not return FALSE if is used with empty string. Yes, it
is documented behaviour (If $string is less than or equal to $start
characters long, FALSE will be returned), but it is not expected
behaviour. There is no way to use "smaller $start".









Test script:
---------------
substr('x', 0, 2) // returns again 'x'



substr('', 0, 2) // returns FALSE but '' is expected



------------------------------------------------------------------------



-- 
Edit this bug report at http://bugs.php.net/bug.php?id=52628&edit=1

Reply via email to