Page 1 of 1

problem with 'switch' and strings

Posted: Sun Sep 07, 2003 12:34 pm
by Stoneguard
Ok, I have written an initialization function for database fields, I was trying to use a switch statement to check the field type. The basic php code is:

Code: Select all

<?php
   function initialize($fldtype)
   {
      switch ($fldype)
      {
         case "string":
         case "blob":
         case "datetime":
            $ini =  "''";
            break;
         case "int":
            $ini = 0;
            break;
         case "real":
            $ini = 0.0;
            break;
         case "text":
            $ini = "''";
            break;
         default:
            $ini = 1;
      }

      return $ini;
   }
?>
If I make the following calls:

Code: Select all

<?php
print initialize('int');   // prints 1
print initialize('blob'); // prints 1
?>
I get a return value of 1 for each. However, if I use a typical if...elseif, I get the proper values returned. Does switch only work for integer values or something? The documentation does not elude to it NOT working for strings.

Posted: Sun Sep 07, 2003 1:33 pm
by mudkicker
after default:
$ini = 1;

yoıu have to write break; !!!

Posted: Sun Sep 07, 2003 1:39 pm
by Stoneguard
Um no, you don't.
The switch statement executes line by line (actually, statement by statement). In the beginning, no code is executed. Only when a case statement is found with a value that matches the value of the switch expression does PHP begin to execute the statements. PHP continues to execute the statements until the end of the switch block, or the first time it sees a break statement. If you don't write a break statement at the end of a case's statement list, PHP will go on executing the statements of the following case.
The default is the LAST statment in the sequence. If 'int' is encountered, the break; bypasses all subsequent statements within the switch.

Posted: Sun Sep 07, 2003 1:39 pm
by Stoneguard
removed for double post

Posted: Mon Sep 08, 2003 5:47 am
by twigletmac
There's a typo on this line:

Code: Select all

switch ($fldype)
it should be

Code: Select all

switch ($fldtype)
When I fix that I get the expected result.

Mac

Posted: Mon Sep 08, 2003 7:14 am
by Stoneguard
doh! I wish there was some way to check silly stuff like that. Thanks, from an extremely embarrased programmer. :roll:

Posted: Mon Sep 08, 2003 7:28 am
by twigletmac
Turn your error reporting up to E_ALL and then you'll get 'undefined variable' warnings for typos like this. It can save a number of headaches.

Mac

Posted: Mon Sep 08, 2003 7:38 am
by Stoneguard
Thanks! I will definitely do that. I have been working with PHP only a few weeks now, but other than some small quirks, I find it an awesome language to work with :)