note 63269 added to function.substr
| From: | rodrigo at fabricadeideias dot com | Date: | Fri, 17 Mar 2006 21:17:16 +0000 |
| Subject: | note 63269 added to function.substr | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-106000@lists.php.net to get a copy of this message | ||
It might be obvious to some but I took some time to figure it out that you can't call
<?php
$text = substr($text, 0, -0);
?>
and expect $text to be unchanged.
A bit of context might make the issue clearer. I'm calculating how many characters I need to
chop of the end of the string and them I call substr as
<?php
$text = substr($text, 0, -$charactersToChop);
?>
Sometimes $charactersToChop is set to 0 and in this case I wanted $text to be unchanged. The problem
is that in this case $text gets set to an empty string.
Why? Because -0 is the same as 0 and substr($text, 0, 0) obviously returns an empty string.
In case someone want a fix:
<?php
if ($charactersToChop) {
$text = substr($text, 0, -$charactersToChop);
}
?>
That's it.
----
Server IP: 200.185.109.101
Probable Submitter: 200.140.12.19 (proxied: unknown)
----
X-Spam-Status: No, hits=3.1 required=5.0 tests=DATE_MISSING,FROM_NO_LOWER
autolearn=no version=2.64
----
Manual Page -- http://www.php.net/manual/en/function.substr.php
Edit -- http://master.php.net/note/edit/63269
Del: integrated -- http://master.php.net/note/delete/63269/integrated
Del: useless -- http://master.php.net/note/delete/63269/useless
Del: bad code -- http://master.php.net/note/delete/63269/bad+code
Del: spam -- http://master.php.net/note/delete/63269/spam
Del: non-english -- http://master.php.net/note/delete/63269/non-english
Del: in docs -- http://master.php.net/note/delete/63269/in+docs
Del: other reasons-- http://master.php.net/note/delete/63269
Reject -- http://master.php.net/note/reject/63269
Search -- http://master.php.net/manage/user-notes.php