switch strange behavior with comparision

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
disputable
Forum Newbie
Posts: 1
Joined: Wed May 26, 2010 7:23 am

switch strange behavior with comparision

Post 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!
User avatar
Weirdan
Moderator
Posts: 5978
Joined: Mon Nov 03, 2003 6:13 pm
Location: Odessa, Ukraine

Re: switch strange behavior with comparision

Post 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.
Post Reply