Toggle Invalid Value

I have a switch statement to show the grade based on the points the students got.

students with points> = 80 get A
students with points> = 70 get B
students with points> = 50 get C
students with glasses> = 30 get D
students with points> = 0 get E

The problem is that the point is 0, it returns A instead of E. Here is the switch .

 $point = 0; switch ($point) { case $point >= 80: echo 'A'; break; case $point >= 70: echo 'B'; break; case $point >= 50: return 'C'; break; case $point >= 30: echo 'D'; break; case $point >= 0: echo 'E'; break; default: echo 'F'; break; } 
+5
source share
5 answers

You are trying to compare $point with a boolean (e.g. $point >= 80 ). This corresponds to the first case, because $point = 0 is false, and $point >= 80 also false, so it corresponds to the first case and the echo A If you want to use case-by-case comparison, you should use the following code:

 $point = 0; switch (true) { case $point >= 80: echo 'A'; break; case $point >= 70: echo 'B'; break; case $point >= 50: echo 'C'; break; case $point >= 30: echo 'D'; break; case $point >= 0: echo 'E'; break; default: echo 'F'; break; } 

demo: https://ideone.com/lyBUmA

Another solution using if and elseif instead of switch :

 $point = 0; if ($point >= 80) { echo 'A'; } elseif ($point >= 70) { echo 'B'; } elseif ($point >= 50) { echo 'C'; } elseif ($point >= 30) { echo 'D'; } elseif ($point >= 0) { echo 'E'; } else { echo 'F'; } 

demo: https://ideone.com/FRlorS

+5
source

This will not work, you are trying to use a logical condition. Use if else instead.

+1
source

yes, obviously, this question is repeated. instead of using

switch ($ point)

you should use

switch (true)

and it works, I checked

 <?php $point = 0; switch (true) { case $point >= 80: echo 'A'; break; case $point >= 70: echo 'B'; break; case $point >= 50: return 'C'; break; case $point >= 30: echo 'D'; break; case $point >= 0: echo 'E'; break; default: echo 'F'; break; } 

For more details, please check this question.

+1
source

You can use 2 comparisons in the case, for example:

 case $point >= 80: echo 'A'; break; case ($point < 80 && $point >= 70): echo 'B'; break; 

etc.

0
source

Switch / Case does not support> ... Try if / elseif ....

 $point = 0; if ($point >= 80) echo 'A'; elseif ($point >= 70) echo 'B'; elseif ($point >= 50) echo 'C'; elseif ($point >= 30) echo 'D'; elseif ($point >= 0) echo 'E'; else echo 'F'; 
0
source

Source: https://habr.com/ru/post/1272870/


All Articles