Re: switch vs elseif

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



Micah Gersten wrote:
> Jochem Maas wrote:
>> switch (true) {
>> 	case ($x === $y):
>> 		// something
>> 		break;
>>
>> 	case ($a != $b):
>> 		// something
>> 		break;
>>
>> 	case (myFunc()):
>> 		// something
>> 		break;
>>
>> 	case ($my->getChild()->hasEatenBeans()):
>> 		// something
>> 		break;
>> }
>>
>> evil ... but it works.
>>
>>
>>   
>>   
> This is a misuse of the switch statement.  Switch is meant to compare
> values to a single variable as stated on the manual page:
> http://us2.php.net/switch
> 
> Thank you,
> Micah Gersten
> onShore Networks
> Internal Developer
> http://www.onshore.com
> 

Actually, if you read the link you posted, the first paragraph: "In many
occasions, you may want to compare the same variable (or expression)
with many different values, and execute a different piece of code
depending on which value it equals to. This is exactly what the switch
statement is for."

Notice the (or expression), which I believe true is one.

Also, down the page: "The case expression may be any expression that
evaluates to a simple type, that is, integer or floating-point numbers
and strings. Arrays or objects cannot be used here unless they are
dereferenced to a simple type."

I believe boolean is also one.

I would point out however that the switch does a loose comparison, so
this would be different:

switch (true) {
	case (strpos("shawn", "s")):
	//actually returns 0 so is false
	break;

	case (strpos("shawn", "s") !== false):
	//returns true
	break;
}

-- 
Thanks!
-Shawn
http://www.spidean.com

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php


[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux