Page 1 of 1

False positives w/ switch

Posted: Fri Aug 11, 2006 2:51 pm
by bakachan
Weirdan | Please use

Code: Select all

,

Code: Select all

and [syntax="..."] tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read:  [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url] to learn how to do it too.[/color]


Sorry about the subject, I don't know how else to describe it.

Code: Select all

<?php
$filename = "5";
$i = $_GET['id'];
switch ($i) {
case 0:
   $filename = "server0.php";
   break;
case 1:
 $filename = "server1.php";
   break;
case 2:
 $filename = "server2.php";
   break;
}

echo $filename;

?>
This is my code. When ever I try 0, 1, or 2 it works. Printing out the correct number, and if I use a number that's not in there(since I have no default set.) It echos nothing. My problem is that when I try something like "cat" it always activates case 0.

I read a little about this, and tried switch(true) and case $i === 0, which is suposed to check for that type only. That didn't work. Why is this so hard? I even tried it with a few if statements. They ALSO saw cat as 0. What's going on here? How did such a simple concept as comparison in other languages become such a challenge in PHP to understand?


Weirdan | Please use

Code: Select all

,

Code: Select all

and [syntax="..."] tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read:  [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url] to learn how to do it too.[/color]

Posted: Fri Aug 11, 2006 2:56 pm
by Weirdan
php is dynamically typed language, so its operations/expressions are subject to type juggling

Side note: anything you got from $_GET/$_POST/$_REQUEST is a string, so strict comparision with integer would always evaluate to false

Posted: Fri Aug 11, 2006 2:57 pm
by bakachan
Thanks on that last comment. I was just about to edit my post saying I came across that. :D I'll check out this jugling.

EDIT: Sorry about the formatting error. I read through the page before and must of misunderstood what you meant by the tags. I'll get it right from now on.

Also this is what I'm thinking. Could I take the string, from the get and do a + 0 to force php to turn it into a float? Then would I be able to use the === to test it? Or do I have to do somethign like a parseint? Even so, what would happen when I tried that with a string like "cat"?

Posted: Fri Aug 11, 2006 3:27 pm
by nincha
if you're expecting a number, make sures its a number.... good coding practice, an important one actually.

Posted: Fri Aug 11, 2006 3:32 pm
by Weirdan
Even so, what would happen when I tried that with a string like "cat"?
'cat' would get converted to zero
in php parseInt is called intval()

Posted: Fri Aug 11, 2006 5:58 pm
by Benjamin
Simple fix is to add some single quotes around your integers in the switch.