0

I not understand little bit. Simple switch statement not working correctly with zero value (=0):

//$result = $sql->fetchColumn(); 
$result = 1;
      switch ($result) {    
          case $result <= 2 :
              throw new Exception('Error!');
              break;
                        }

Problem is when $result = 0 then output should be 'error' but in this case script passing this validation. Weird question but i can't find a problem.

5
  • A normal IF statement should be your friend in that case Commented Mar 1, 2017 at 12:21
  • This is just a fragment of the code. I need to find out why that's happens Commented Mar 1, 2017 at 12:23
  • 2
    You haven't understand how switch statement works. You can't execute a "greater than... less than" etc. in a switch statement. You can only do a case for a specific number. us2.php.net/manual/en/control-structures.switch.php Commented Mar 1, 2017 at 12:25
  • Ok i understand now Commented Mar 1, 2017 at 12:26
  • I've posted an answer that shows you how you can do it with a switch-statement. :) Hope you'll find your solution. If you need more help, feel free to ask. Commented Mar 1, 2017 at 12:28

2 Answers 2

1

You can write it like that:

<?php
switch ($i) {
case 0:
case 1:
case 2:
    throw new Exception('Error!');
    break;
case 3:
    echo "i is 3 or higher.";
}
?>

As I said in my comment above, you can't use "grater than" "less than" etc. in a switch-statement. As other said, if you want to make use of them, use a simple IF statement.

Sign up to request clarification or add additional context in comments.

Comments

0

this code

switch ($result) {    
      case $result <= 2 :

is equivalent

if($result == ($result <= 2))

and when

$result=0 

we have

( 0 == true ) 

after type conversion

false === true

and this is false as expected

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.