Page 1 of 1

switch strange behavior with comparision

Posted: Wed May 26, 2010 7:31 am
by disputable
Hi there...

Here's a small snippet of PHP code:

Code: Select all

$var1 = 0;
$var2 = 5;
		
switch($var1)
{
	case ($var1 >= $var2):
		echo 'case1';
		break;
	
	case 5:
		echo 'case2';
		break;
	
	default:
		echo 'default';
		break;
}
this code allways returns "case1". isn't that wrong?
i allways thought that it should return "default". It does so if $var1 is one or two or something like that but not with zero..

Thanks for your ideas!

Re: switch strange behavior with comparision

Posted: Wed May 26, 2010 7:35 am
by Weirdan
switch evaluates it's condition and then compares it to case conditions. So you're comparing 0 with (0 >= 5). (0 >= 5) == false == 0. Thus the first case satisfies the comparison.