note 34020 modified in control-structures.switch by vrana

From: Date: Tue, 17 Aug 2004 13:54:31 +0000
Subject: note 34020 modified in control-structures.switch by vrana
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-80052@lists.php.net to get a copy of this message
As jason at devnetwork dot net and others have pointed out, using switch() when you wish to compare against strings can be dangerous: <?php $bug = 0; switch ($bug) { case 'fly': echo 'flies buzz'; break; case 'mantis': echo 'mantes pray'; break; default: echo 'swat, splat, you are dead'; break; } ?> Will print "flies buzz", NOT "swat, splat, you are dead". Remember PHP says that 'fly' == 0, or in general string == 0 is true. Anyway, avoid that with: <?php $bug = 0; switch ($bug === 0 ? '' : $bug) { case 'fly': echo 'flies buzz'; break; case 'mantis': echo 'mantes pray'; break; default: echo 'swat, splat, you are dead'; break; } ?> Prints out what you expect: Swat Splat You are dead P.S.: that's an empty string (single quote single quote), not a spurious double quote. --was-- As jason at devnetwork dot net and others have pointed out, using switch() when you wish to compare against strings can be dangerous: $bug = 0; switch ($bug) { case 'fly': echo 'flies buzz'; break; case 'mantis': echo 'mantes pray'; break; default: echo 'swat, splat, you are dead'; break; } Will print "flies buzz", NOT "swat, splat, you are dead". Remember PHP says that 'fly' == 0, or in general string == 0 is true. Anyway, avoid that with: $bug = 0; switch ($bug === 0 ? '' : $bug) { case 'fly': echo 'flies buzz'; break; case 'mantis': echo 'mantes pray'; break; default: echo 'swat, splat, you are dead'; break; } Prints out what you expect: Swat Splat You are dead P.S.: that's an empty string (single quote single quote), not a spurious double quote. http://php.net/manual/en/control-structures.switch.php

« previous php.notes (#80052) next »