Page 1 of 1

CASE: NULL [SOLVED]

Posted: Tue May 02, 2006 2:11 pm
by tomprogers
I have a boolean field in my database. Based on the value of the field (NULL/0/1), I want to take different actions. I use a switch, like so:

Code: Select all

switch($boolean)
case 0: /* do something for records that have been assigned a 0 value */ break;
case 1: /* do something for records that have been assigned a 1 value */ break;
case NULL: /* do something for records that have not been assigned a value yet */ break;
Unfortunately, it seems that a DB value of NULL is not being converted to PHP's NULL, and is instead matching the 0 case. This means I can't replace my case NULL with a plain default either - NULL will still trip the case 0. I checked the pg_fetch_array documentation, and it said that it is supposed to be properly preserving NULL values.

Am I overlooking something, or can I not use a switch?


Edit: I tried explicitly setting $var = NULL and switching on it, and it still equated 0 with NULL, regardless of the order of the case statements.

Posted: Tue May 02, 2006 2:43 pm
by Christopher
Null technically means is not set, so switch cannot switch on it and the check should probably be:

Code: Select all

if(isset($boolean)) {
    switch($boolean) {
    case 0: /* do something for records that have been assigned a 0 value */ break;
    case 1: /* do something for records that have been assigned a 1 value */ break;
    }
} else {
    /* do something for records that have not been assigned a value yet */ break; 
}
Which is:

Code: Select all

if(isset($boolean)) {
    if ($boolean) {
        /* do something for records that have been assigned a 0 value */ break;
    } else {
        /* do something for records that have been assigned a 1 value */ break;
    }
} else {
    /* do something for records that have not been assigned a value yet */ break; 
}
But you would really need to see what is being returned by the fetch().

Posted: Tue May 02, 2006 2:45 pm
by tomprogers
Fair enough. I'd already switch to a if-else block with a ternary statement to keep things short, but it's good to know why this is a problem.

Thanks.

Posted: Tue May 02, 2006 5:52 pm
by Chris Corbyn
tomprogers wrote:Fair enough. I'd already switch to a if-else block with a ternary statement to keep things short, but it's good to know why this is a problem.

Thanks.
<Opinion only>
Use ternary statements sparingly.... they can get messy and difficult to make sense of in larger scripts.
</Opinion>

Posted: Tue May 02, 2006 6:20 pm
by Ollie Saunders
<Opinion only>
Use ternary statements sparingly.... they can get messy and difficult to make sense of in larger scripts.
</Opinion>
I share that opinion.