switch issue
am 06.01.2008 23:29:34 von sublimino
Hello all,
Having a problem with the behaviour of switch when mixing variable types. Eg
$page = 'review';
switch ($page) {
case 0:
echo "0";
break;
case 'review':
echo "review";
break;
}
?>
this code interprets $page as 0 in the switch. It's not a problem to
alter 'review' to a number, just less elegant. Can anybody shed a
little light on mixed variable types in switch statements please?
While browsing the manual I noticed it performs "loose comparison" but
that seems to be the same as == ?
Many thanks,
Andy
--
PHP Database Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php
Re: switch issue
am 06.01.2008 23:51:46 von dmagick
sublimino@gmail.com wrote:
> Hello all,
>
> Having a problem with the behaviour of switch when mixing variable types. Eg
>
>
> $page = 'review';
> switch ($page) {
> case 0:
> echo "0";
> break;
> case 'review':
> echo "review";
> break;
> }
> ?>
>
> this code interprets $page as 0 in the switch. It's not a problem to
> alter 'review' to a number, just less elegant. Can anybody shed a
> little light on mixed variable types in switch statements please?
> While browsing the manual I noticed it performs "loose comparison" but
> that seems to be the same as == ?
My guess is that it's converting '$page' from a string to an int to do
the comparison because you don't have quotes around it.
If you do:
echo (int)'review';
you get 0.
If you look at the Loose Comparisons table here:
http://www.php.net/manual/en/types.comparisons.php#types.com parisions-loose
In the "php" column (second from the right), when compared to 0 without
quotes it evaluates to true, so it's expected behaviour.
So change it to:
case '0':
echo '0';
break;
--
Postgresql & php tutorials
http://www.designmagick.com/
--
PHP Database Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php