Basic switch statement

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

 



I'm new to programming, drive a truck in the day, now taking night courses
to get a better job for my family.  Please bear with me if this is a dumb
question, I don't have much experience.

I'm taking a night class in HTML and PHP and can't figure out a problem and
can't find the answer in the book for the course ("Beginning PHP5" by Wrox
Press), on the switch manual page on php.net, or in any postings to this
mailing list.

I'm trying to pass a value to a simple integer to a function, and then use
that value in a switch statement.  The problem I'm having is that regardless
of the value of 'val', the first case statement always executes.  Even if I
put '$val = 0' right before the case statement, the first case statement
executes.  The syntax looks correct based on the php.net man page for switch
and from the user examples.  It also matches the example in the book.

function check_it2($val) {
    echo gettype($val);
    switch($val) {
        case($val > 0 ):
            echo "Switch greater than 0";
            $diff_obj = 1;
            break;
        case($val < 0 ):
            echo "Less than 0";
            $diff_obj = -1;
            break;
        default:
            echo "Equal to 0";
            $diff_obj = 0;
    }
    print("Here's \$diff_obj2 in the function: " . $diff_obj);
    return $diff_obj;
}

I even put the following code before the switch statement just to make sure
I'm not crazy:

    $val = 0;
    if($val > 0) {
        echo "If greater than 0";
    }
    else {
        echo "If not greater than 0";
    }

and it falls through to the else as it should.

I've tried putting single and double quotes around the case variables but it
always prints out the first value.  I've recoded to use a series of if
statements but why isn't the switch working?   I've read through the 'loose
comparison' section, but nothing appears to apply there.

Sorry for the basic question.

Steve Reilly

[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