FUDforum
Fast Uncompromising Discussions. FUDforum will get your users talking.

Home » Imported messages » comp.lang.php » switch with case 0
Show: Today's Messages :: Polls :: Message Navigator
Return to the default flat view Create a new topic Submit Reply
Re: switch with case 0 [message #182590 is a reply to message #182589] Sat, 17 August 2013 06:35 Go to previous messageGo to previous message
J.O. Aho is currently offline  J.O. Aho
Messages: 194
Registered: September 2010
Karma:
Senior Member
On 17/08/13 06:55, Fiver wrote:
> This example
>
> switch ("foo") {
> case 0:
> echo "'foo' is 0\n";
> break;
> default:
> echo "'foo' is not 0\n";
> }
>
> will print: 'foo' is 0.

The switch you are doing is equal to a

if("foo" == 0) {}

PHP will make a type casting and try to make the "foo" to a integer, as
it's not a string only of numeric characters and those it will be cast
to a 0 which makes your statement true.


You can try this one:

switch("123") {
case 0:
echo "it's 0\n";
break;

case 123:
echo "it's 123\n";
break;

default:
echo "it's NOT 0 nor 123\n";
}


> I know how to avoid the problem, I'm just wondering what kind of
> comparison is used that makes "foo" equal to 0? The manual mentions
> "loose comparison", but this is even looser than usual.

No it's not looser than normally, PHP don't care so much about data
types so it internally casts it just to make it easy for those who ain't
so good at programming.


> By the way, the original code was meant to validate SORT_* arguments.
> It's a little harder to spot here:
>
> switch ($mode) {
> case SORT_ASC:
> case SORT_DESC:
> case SORT_REGULAR:
> case SORT_NUMERIC:
> case SORT_STRING:
> case SORT_LOCALE_STRING:
> case SORT_NATURAL:
> case SORT_FLAG_CASE:
> break;
> default:
> throw new \InvalidArgumentException("invalid sort mode: $mode");
> }
>
> SORT_REGULAR is 0, so if the input is a string, this will break (literally).

Sounds like you are trusting user input, always validate the user input
to be a valid value of the type you are requiring. In this case
is_numeric() could save you from trouble.

--

//Aho
[Message index]
 
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Previous Topic: AND and OR
Next Topic: Compiling PHP 5.x on Cygwin
Goto Forum:
  

-=] Back to Top [=-
[ Syndicate this forum (XML) ] [ RSS ]

Current Time: Wed Nov 27 11:53:52 GMT 2024

Total time taken to generate the page: 0.04223 seconds