PHP script error when value is zero - php

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.

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.

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

Related

PHP switch syntax [duplicate]

This question already has answers here:
Conditional switch statements in PHP
(5 answers)
Closed 4 years ago.
I am a NOOB with PHP and trying to figure out the SWITCH syntax.
I know how to do the case statement like the following:
$numbr = 2;
switch ($numbr) {
case 2:
echo "numbr is equal to 2";
break;
case 1:
echo "numbr is 1";
break;
}
but if I use this instead (checking for a number greater than 1) it breaks. What am I doing wrong?
$numbr = 2;
switch ($numbr) {
case >1:
echo "numbr is greater than 1";
break;
case 1:
echo "numbr is 1";
break;
}
Switch statements are not good to use in these cases, instead, you should use if/else.
if($numbr > 1) {
echo "numbr is greater than 1";
} else if($numbr == 1) {
echo "numbr is 1";
}
Switches are most useful when comparing a value to many other values, not for comparing a value with a mathematical expression or logic.
It's better to use switches than if statements when possible, because switch statements are only evaluated once, whereas if statements are evaluated for every if().
You can't put that as a case, there must be a value.
A good solution could be this one, but only for positive values:
$numbr = 2;
switch ($numbr) {
case 0:
break;
case 1:
echo "numbr is 1";
break;
default:
echo "numbr is greater than 1";
break;
}
If you want to handle also negative values you need to use if/else as others said

PHP switch and if statement output different results

Could someone please explain what's going on here?
Here's the code:
$num = 0;
switch($num){
case ($num==0):
echo $num , " is ZERO";
break;
case ($num>0):
echo $num , " is POSITIVE";
break;
default:echo $num , " is NEGATIVE";
}
The above outputs 0 is POSITIVE
if($num==0){
print ($num." is ZERO");
}
elseif($num>0){
echo $num , " is POSITIVE";
}
else{
echo $num , " is NEGATIVE";
}
This works as expected - 0 is ZERO.
If I replace
case($num==0) with case(0) the output is OK.
Why does the case($num==0) fail?
Someone told me the issue with evaluating multiple expressions in the case statements, but it seems fine syntactically.
switch compares everything in the switch (...) expression to each case:
switch ($num) {
case 0 :
...
case 1 :
...
...
}
You don't write case $num == 0, as that's equivalent to if ($num == 0 == $num).
If at all, you'd have to do:
switch (true) {
case $num == 0 :
...
case $num > 0 :
...
...
}
But there are people who frown upon that.
The logical structure of switch operator is this:
switch($x):
case val1:
action 1;
break;
case val2:
action 2;
break;
default:
not val1 and val2;
switch compares $x with one of the values or gives default branch in case nothing matches. So, you can't write:
case ($num > 0):
or
case ($num == 0 ):
In your case it gives POSITIVE, because php first evaluates the expressions inside cases, and we get the following in the output:
Is $num == 0 ?: yes => 1
Is $num > 0 ?: no => 0
And the real switch php evaluates is this:
$num = 0;
switch($num){
case 1:
echo $num , " is ZERO";
break;
case 0:
echo $num , " is POSITIVE";
break;
default:
echo $num , " is NEGATIVE";
}
Output is: POSITIVE.

Why isn't this switch statement return that 0 is in 0-100?

Information
I am currently making a user level system for my website. I have a points column in my users table that will get incremented on certain awards and milestones etc.
Problem
I have this switch statement that takes the users points and converts them into a level that gets returned. But it is saying that "0" isn't in 0-100 option, and rather in the 100-200 option.
function userLevel($points){
switch ($points) {
case ($points>=0 && $points<100):
return 1; // Level 1
break;
case ($points>=100 && $points <200):
return 2; // Level 2
break;
case ($points>=200 && $points<300):
return 3; // Level 3
break;
case ($points>=300 && $points<400):
return 4; // Level 4
break;
}
}
echo userLevel(0);
I feel like this is one of those "You have been coding too much for one sitting" questions and the answer is right in front of me, but I just can't see it!
Since your using conditions for your cases, you probably want to switch on TRUE:
function userLevel($points){
switch (true) {
case ($points>=0 && $points<100):
return 1; // Level 1
break;
case ($points>=100 && $points <200):
return 2; // Level 2
break;
case ($points>=200 && $points<300):
return 3; // Level 3
break;
case ($points>=300 && $points<400):
return 4; // Level 4
break;
}
}
The reason is your code is becoming this
function userLevel($points){
switch (0) {
case (true): // compare 0 to true
return 1; // Level 1
break;
case (false): // compare 0 to false
return 2; // Level 2
break;
case (false):
return 3; // Level 3
break;
case (false):
return 4; // Level 4
break;
}
}
echo userLevel(0);
The first case does not match because 0 != true
the second case does match because 0 == false
Therefore the second option runs
as others have said use true in the switch so then it becomes true == true as the first case, making that run
One other thing you can do to eliminate a lot of code for this is to simply do this
return floor(($points+100)/100);

php switch case problem

I am trying to say $level > -100 && $level < 100
$level = 0;
switch($level){
case $level > -100:
break;
case $level < 100:
break;
default:
echo '5';
return null;
}
can you use a switch statement like this.
None of the answers presented so far have explicitly connected the spirit of the original question with a proper switch construction. So, for the record:
switch (true) {
case (($level>-100) && ($level<100)):
echo 'in range one';
break;
case (($level>200) && ($level<300)):
echo 'in range two';
break;
default:
echo 'out of range';
}
There's absolutely nothing wrong with this usage of switch.
When you say switch ($level) you're already comparing the value of $level. Each case can then only check for equality, you can't do comparisons like in your example. You'll have to use an if statement instead:
if ($level > -100 && $level < 100)
; // do nothing; equivalent of break in this case
else
echo '5';
Even simpler, just negate the conditions:
if ($level <= -100 || $level >= 100)
echo '5';
Apart of if/else, another way to do it:
switch (true)
case $level > -100:
break;
case $level < 100:
break;
default:
echo '5';
return null;
}
The other answers are both correct and incorrect at the same time. Incorrect, in that it is possible to do what you want in PHP... change switch($level) to switch(true) and your example will work. Correct, in that it's bad form and if any other programmers see that in your code they'll probably come after you with pitchforks. Its not how the switch statement is intended to be used, and wouldn't work like that in most other languages.
No you can't. Switch does only 'equals' type comparison.
No, you can't. The switch statement needs literals in the case blocks. Use an if statements instead:
if(!($level > -100 && $level < 100))
{
echo '5';
return null;
}
This is one of the reasons people advocating case as a superior solution to if-else are off base. I don't like the syntax or the limitations - if-ifelse-else is much more useful.

PHP CASE statement not working with ZERO values

I don't understand what's happening here. Logically, it doesn't make any sense to me.
<?php
$level = 0;
switch ($level) {
case $level > 80: $answer = 'high'; break;
case $level > 60: $answer = 'moderate-to-high'; break;
case $level > 40: $answer = 'moderate'; break;
case $level > 20: $answer = 'low-to-moderate'; break;
default: $answer = 'low'; break;
}
echo $answer;
?>
When $level == 0, it returns "high". This doesn't make any sense to me. Can someone explain what's happening here?
Change switch ($level) to switch (true) and this will work.
switch statements perform equality tests on the values in the cases. PHP is evaluating your > comparisons, so case $level > 80 becomes case false. false is considered to be equal to 0, so the first case matches.
The quantity after the case needs to be just the value, not a boolean expression. I'm guessing that PHP is evaluating case $level > 80 as case ($level > 80) which is becoming case 0 (i.e., false, since $level is indeed NOT less than 80) and so you're matching the first case.
Are you sure you can do this in php?
I just checked the manual of switch and you have to provide a distinct value.
I think if you can write it again into something like:
$levelDivTwenty = intval($level/20);
$levelDivTwenty = ($levelDivTwenty>4)?4:$levelDivTwenty;
and then case on that.
switch ($levelDivTwenty) {
case 4: //same as $level > 80 before...
case 3: //>60 etc...
}
As others have pointed out you can't use switch like that, but how about defining it like this:
<?
$level = 21;
$answers = array('low', 'low-to-moderate',
'moderate', 'moderate-to-high', 'high');
echo $answers[intval(($level-1)/20)];
?>
Note: If $level = 0, then expression inside intval() will be -1/20, which is less then -1 and therefore will be rounded to 0.
This isn't really how switch is intended to be used. It's to evaluate for a specific value.
Use an If/else if here, instead of complicating your life to make a switch work like one.

Categories