Re: Basic switch statement
| From: | Robert Cummings | Date: | Tue, 13 Apr 2010 21:06:30 +0000 |
| Subject: | Re: Basic switch statement | ||
| References: | 1 2 3 4 5 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-304070@lists.php.net to get a copy of this message | ||
Nathan Rixham wrote:
Robert Cummings wrote:Well you DID get 66.7%. I've met "coders" that would stare at the answer and still not understand :D Cheers, Rob. -- http://www.interjinn.com Application and Templating Framework for PHPNathan Rixham wrote:well that's one job I'm not getting :pRobert Cummings wrote:Fail on that last one. -1 is not equivalent to FALSE :Bsteve_r wrote:This is a fantastic example of false logic and an easy pitfall. in fact this would make a great interview question! to expand a little on the various scenarios (just for clarity, Rob is right) $val = 1; 1 > 0 equates to TRUE is 1 equivalent to TRUE : YES $val = 0; 0 > 0 equates to FALSE is 0 equivalent to FALSE : YES $val = -1; -1 > 0 equates to FALSE is -1 equivalent to FALSE: YES so no matter what value you set $val to; it's always true.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) {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.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;}