On Tue, 2010-04-13 at 12:04 -0400, 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; > } > > 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 Change the first line of the switch to switch(true) and it will be functioning as you want. Normally, a switch has this form: switch($val) { case 1: { // statements break; } case 10: { // statements break; } default: { // statements } } But PHP does allow you to use variable cases (as you have in your example) if the value in the switch is a boolean (true or false). It can be a little confusing if you're new to PHP (or programming in general) but you'll get used to it after using it a few times. Thanks, Ash http://www.ashleysheridan.co.uk