note 63269 deleted from function.substr by danbrown

From: Date: Fri, 28 Nov 2008 20:20:59 +0000
Subject: note 63269 deleted from function.substr by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-147201@lists.php.net to get a copy of this message
Note Submitter: rodrigo at fabricadeideias dot com ---- 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.

« previous php.notes (#147201) next »