Re: Basic switch statement

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

 



steve_r wrote:
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;
}

You're a tad confused :)

Q: What is the result of $val > 0?
A: false.

Q: What is the value of $val?
A: 0

Q: Is 0 equivalent to false?
A: Yes!

Use an if statement for this kind of logic.

Cheers,
Rob.
--
http://www.interjinn.com
Application and Templating Framework for PHP

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php


[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