The switch-case failing [duplicate] - php

This question already has answers here:
Switch doesn't work with numeric comparison cases
(4 answers)
Closed 8 years ago.
I have a function like this:
public static function GetNilaiHuruf($nilai)
{
if($nilai > 4)
{
$nilai = (float) ((float)($nilai) / (float)(100.0) * (float)4.0);
}
switch($nilai)
{
case ($nilai > 3.66 && $nilai <= 4) :
return "A";
break;
case ($nilai > 3.33 && $nilai <= 3.66) :
return "A-";
break;
case ($nilai > 3.00 && $nilai <= 3.33) :
return 'B+';
break;
case ($nilai > 2.66 && $nilai <= 3.00) :
return 'B';
break;
case ($nilai > 2.33 && $nilai <= 2.66) :
return 'B-';
break;
case ($nilai > 2.00 && $nilai <= 2.33) :
return 'C+';
break;
case ($nilai > 1.66 && $nilai <= 2.00) :
return 'C';
break;
case ($nilai > 1.33 && $nilai <= 1.66) :
return 'C-';
break;
case ($nilai > 1.00 && $nilai <= 1.33) :
return 'D+';
break;
case ($nilai >= 0.00 && $nilai <= 1.00) :
return 'D';
break;
}
}
When I call that function with $nilai is 0, the function returns 'A';
When I call that function with $nilai is 0.007 or 'x', the function returns 'D'.
How is that possible?

That is not how switch statements work, they shouldn't be used to do numeric comparisons like that.
However, you can achieve what you want by using boolean true as your switch argument:
$yourvar = -20;
switch(true) {
case ($yourvar > 0 && $yourvar < 5) :
echo 'Hello world!';
break;
case ($yourvar < 0) :
echo 'Hello hell!';
break;
}
// Hello hell!
Please see this article for more info.

There's no need to try to use a switch here. Use if/else if/else:
if ($nilai > 3.66 && $nilai <= 4) {
return "A";
} else if ($nilai > 3.33 && $nilai <= 3.66) {
return "A-";
} ...

Related

Condition statement

I am trying to generate a report book based on marks scored by a student. In the form I have a checkbox from which a teacher can tick if a student was absent and if that is the case then the value for the MARK must change to AB and COMMENT as ABSENT, while it is able to change the value to "AB", this code is unable to provide a comment that the student was "ABSENT" instead it puts "FAIL" as a comment. What should I change in the code.
if (isset($_POST['absent']) && (empty($mark)))
{
$mark="AB";
$comment="Absent";
}
if($mark < 101 && $mark >=0)
{ $comment="";
if($grade > 9){
$score="";
if($mark >=75 and $mark <= 100 ){
$score=1;
$comment="Distinction";
}else if($mark >= 70 and $mark <=74){
$score=2;
$comment="Distinction";
}else if($mark >= 65 and $mark <= 69 ){
$score=3;
$comment="Merit";
}else if($mark >= 60 and $mark <=64){
$score=4;
$comment="Merit";
}else if($mark >= 55 and $mark <= 59){
$score=5;
$comment="Credit";
}else if($mark >= 50 and $mark <= 54){
$score=6;
$comment="Credit";
}else if($mark >= 45 and $mark <= 49){
$score=7;
$comment="Pass";
}else if($mark >= 40 and $mark <= 44){
$score=8;
$comment="Pass";
}else if($mark >= 0 and $mark <=39){
$score=9;
$comment="Fail";
}else if($mark=="AB"){
$comment="Absent";
}
Else and If used in this repetative way is pretty inefficient. Here is a suggestion to use switch. In PHP 8+ you can possibly also use match. Switch is more efficient because it only checks the value of the testing variable ($mark) once, rather than repeatedly .
$comment=""; //default.
if (isset($_POST['absent']) && (empty($mark)))
{
$mark="AB";
$comment="Absent"; //default.
}
switch((int)$mark < 101 && $grade > 9) {
case in_array($mark, range(75,100)):
$score=1;
$comment="Distinction";
break;
case in_array($mark, range(70,74)):
$score=2;
$comment="Distinction";
break;
case in_array($mark, range(65,69)):
$score=3;
$comment="Merit";
break;
case in_array($mark, range(60,64)):
$score=4;
$comment="Merit";
break;
case in_array($mark, range(55,59)):
$score=5;
$comment="Credit";
break;
case in_array($mark, range(50,54)):
$score=6;
$comment="Credit";
break;
case in_array($mark, range(45,49)):
$score=7;
$comment="Pass";
break;
case in_array($mark, range(40,44)):
$score=8;
$comment="Pass";
break;
case in_array($mark, range(0,39)):
$score=9;
$comment="Fail";
break;
}

Binding parameters in switch statement

I need a little helping hand in my script. As the title suggests it's about parameters. I have this code:
if (isset($_GET['sendit'])) {
$theusersname = $_GET['theusersname'];
$totalmarks = $_GET['totalmarks'];
$mathsobt = $_GET['mathsobt'];
$physicsobt = $_GET['physicsobt'];
$chemistryobt = $_GET['chemistryobt'];
$computerobt = $_GET['computerobt'];
$englishobt = $_GET['englishobt'];
$totalobt = $mathsobt + $physicsobt + $chemistryobt + $computerobt + $englishobt;
$modulo = ($totalobt / $totalmarks) * 100;
$grade = "";
//for grades
switch ($modulo, $grade) {
case 'A-1'://100% ro 80%
if ($modulo >= 79.5 && $modulo <= 100){
$grade = "A-1";
}
break;
case 'A'://79% to 70%
if ($modulo >= 69.5 && $modulo <= 79.4) {
$grade = "A";
}
break;
case 'B'://69 to 60
if ($modulo >= 59.5 && $modulo <= 69.4){
$grade = "B";
}
break;
case 'C'://59 to 50
if ($modulo >= 49.5 && $modulo <= 59.4){
$grade = "C";
}
break;
case 'D'://49 to 40
if ($modulo >= 39.5 && $modulo <= 49.4){
$grade = "D";
}
break;
case 'F'://32 to rest
if ($modulo >= 33 && $modulo <= 39.4){
$grade = "F";
}
default:
if ($modulo >= 0 && $modulo <= 32.9){
$grade = "N/A";
}
break;
}
//for remarks
switch ($grade) {
case '':
break;
default:
break;
}
$query = "INSERT INTO `report`(`name`, `grade`, `total`, `mathsobt`, `physicsobt`, `chemistryobt`, `computerobt`, `englishobt`, `totalobt`, `modulo`, `remarks`) VALUES ('$theusersname', '$grade', '$totalmarks', '$mathsobt', '$physicsobt', '$chemistryobt', '$computerobt', '$englishobt', '$totalobt', '$modulo', '$remarks')";
$result = mysqli_query($mysqliConn, $query);
// if (mysqli_query($mysqliConn, $query)) {
// echo "New record created successfully";
// } else {
// echo "Error: " . $query . "<br>" . mysqli_error($mysqliConn);
$mysqliConn->close();
// }
The grading switch statement doesn't work. Because I just can't get what parameter I need to give. Same goes for the remarks too. The code may be terrible and don't have sanitization (which in this case I don't need). I'm also a little bit confuse with the strings I passed for cases. I mean does it have an effect on overall?
Thank you.
PS: If there is already a similar answer out there, which i unfortunately i didn't find, i'm ready to view the link. Please post a little explanatory comment.
$modulo && $grade is a boolean expression. Its value is either TRUE or FALSE (and not 'A', 'B' or 'C').
But PHP is a loose-type language and it changes the types of its values as needed before using them. Because of this, 'A' == TRUE and '' == FALSE and your code produces only 'A-1' and 'N/A' grades.
A switch doesn't help here. You should use a sequence of cascaded ifs:
if ($modulo >= 79.5) {
$grade = "A-1";
} elseif ($modulo >= 69.5) {
$grade = "A";
} elseif ($modulo >= 59.5) {
$grade = "B";
} elseif ($modulo >= 49.5) {
$grade = "C";
} elseif ($modulo >= 39.5) {
$grade = "D";
} elseif ($modulo >= 33) {
$grade = "F";
} else {
$grade = "N/A";
}
Read how PHP compare values of different types and read how the switch control structure works.
Here you go
$theusersname = 'theusersname';
$totalmarks = 500;
$mathsobt = 87;
$physicsobt = 82;
$chemistryobt = 75;
$computerobt = 79;
$englishobt = 91;
$totalobt = $mathsobt + $physicsobt + $chemistryobt + $computerobt + $englishobt;
$modulo = ($totalobt / $totalmarks) * 100;
switch ($modulo) {
case $modulo >= 33 && $modulo < 39.5:
$grade = "F";
break;
case $modulo >= 39.5 && $modulo < 49.5:
$grade = "D";
break;
case $modulo >= 49.5 && $modulo < 59.5:
$grade = "C";
break;
case $modulo >= 59.5 && $modulo < 69.5:
$grade = "B";
break;
case $modulo >= 69.5 && $modulo < 79.5:
$grade = "A";
break;
case ($modulo >= 79.5 && $modulo <= 100 ):
$grade = "A-1";
break;
default:
$grade = "N/A";
break;
}
switch ($grade) {
case 'A-1':
$remarks = "You have got A-1 ";
break;
case 'A':
$remarks = "You have got A ";
break;
case 'B':
$remarks = "You have got B ";
break;
case 'C':
$remarks = "You have got C ";
break;
case 'D':
$remarks = "You have got D ";
break;
case 'F':
$remarks = "You have got F ";
break;
default:
$remarks = "You have got nothing";
break;
}
echo $query = "INSERT INTO `report`
(`name`, `grade`, `total`, `mathsobt`, `physicsobt`,
`chemistryobt`, `computerobt`, `englishobt`, `totalobt`,
`modulo`, `remarks`)
VALUES ('$theusersname', '$grade', '$totalmarks', '$mathsobt',
'$physicsobt', '$chemistryobt', '$computerobt', '$englishobt',
'$totalobt', '$modulo', '$remarks')";
OUTPUT
INSERT INTO `report`
(`name`, `grade`, `total`, `mathsobt`, `physicsobt`,
`chemistryobt`, `computerobt`, `englishobt`, `totalobt`,
`modulo`, `remarks`)
VALUES ('theusersname', 'A-1', '500', '87', '82', '75', '79',
'91', '414', '82.8', 'You have got A-1 ')

PHP Switch case & if statement not returning correct values

I'm kind of new to PHP and I'm trying to write a script that counts points after a user inputs values.
Here's the code:
<?php
$pla = $_GET['players'];
$plu = $_GET['plugins'];
$type = $_GET['type'];
$location = $_GET['location'];
totalPoints();
function typePoints($type) { //Returns points depending on server type
switch (strtolower($type)) { //Switch the type of server between all types and see how many points to return :)
case "standard minecraft": return 1;
break;
case "snapshot": return 2;
break;
case "craftbukkit": return 2;
break;
case "bungeecord": return 1;
break;
case "spigot": return 2;
break;
case "paperspigot": return 2;
break;
case "feed the beast": return 3;
break;
case "technic": return 3;
break;
case "pixelmon": return 3;
break;
default: echo 'Incorrect Server Type!';
exit;
break;
}
}
function playerPoints($players) { //Returns points depending on amount o players
if ($players >= 2 && $players <= 5) {
return 2;
} elseif ($players >= 6 && $players <= 10) {
return 4;
} //Between 6-10, return 4 points... AND SO ON...
elseif ($players >= 11 && $players <= 16) {
return 8;
} elseif ($players >= 17 && $players <= 25) {
return 12;
} elseif ($players >= 26 && $players <= 30) {
return 16;
} elseif ($players >= 31 && $players <= 36) {
return 18;
} elseif ($players >= 37 && $players <= 45) {
return 20;
} elseif ($players >= 46 && $players <= 50) {
return 22;
} elseif ($players >= 51 && $players <= 56) {
return 24;
} elseif ($players >= 57 && $players <= 65) {
return 26;
} elseif ($players >= 66 && $players <= 70) {
return 28;
} elseif ($players >= 71 && $players <= 76) {
return 30;
} elseif ($players >= 77 && $players <= 85) {
return 32;
} elseif ($players >= 86 && $players <= 90) {
return 34;
} elseif ($players >= 91 && $players <= 96) {
return 36;
} elseif ($players >= 97 && $players <= 105) {
return 38;
} elseif ($players >= 106 && $players <= 110) {
return 40;
} elseif ($players > 110) {
return 44;
}
}
function pluginPoints($plugins) {
if ($plugins == 0) {
return 0;
} elseif ($plugins >= 1 && $plugins <= 3) {
return 2;
} //Between 1-3, return 2 points.... AND SO ON...
elseif ($plugins >= 4 && $plugins <= 15) {
return 6;
} elseif ($plugins >= 16 && $plugins <= 30) {
return 10;
} elseif ($plugins >= 31 && $plugins <= 40) {
return 14;
} elseif ($plugins >= 41 && $plugins <= 50) {
return 20;
} elseif ($plugins > 50) {
return 24;
}
}
function locationPoints($location) {
switch (strtolower($location)) { //Switch between locations, easy to add a new one later in the future. :)
case "montreal": return 1;
break;
case "france": return 1;
break;
default: echo "Incorrect Location!";
exit;
break;
}
}
function totalPoints() { //Call this function to get the amount of points finally.
$totalPoints = typePoints($type) + playerPoints($pla) + pluginPoints($plu) + locationPoints($location);
echo 'Total points: ' . $totalPoints;
}
?>
The problem is the switch statement in function typePoints($type) always returns the default: echo 'Incorrect Server Type!'; exit; break;.
Also, function playerPoints($players) returns 0 even though I put in a number like 37.
I used this:
http://website.com/planpicker.php?players=121&location=france&plugins=80&type=technic
Can anyone tell me why?
This is not a duplicate question, the "marked duplicate" talks about different files, but this is within the same file.
The 4 variables are not accessible from totalPoints function. You should pass those parameters to function. You should call function as :
totalPoints($type,$pla,$plu,$location);
And define the function as
function totalPoints($type,$pla,$plu,$location)
It's because you call your functions in another function without passing the values in parameter.
The totalPoints function is not aware of the value of $type or $pla for example as they are not GLOBALS.
You have to pass the variables to the function you want to call :
function totalPoints($type, $pla, $plu, $location) //Call this function to get the amount of points finally.
{
$totalPoints = typePoints($type) + playerPoints($pla) + pluginPoints($plu) + locationPoints($location);
echo 'Total points: '.$totalPoints;
}
And then call the function like this :
totalPoints($type,$pla,$plu,$location);
The variables that were decared outside of the functions need to be made accessible to the totalPoints function. The easiest way is to use global
function totalPoints() {
global $pla;
global $plu;
global $type;
global $location;
$totalPoints = typePoints($type) + playerPoints($pla) + pluginPoints($plu) + locationPoints($location);
echo 'Total points: '.$totalPoints;
}

Switch function in PHP

What do I have to write in the cases (of switch function in PHP) to make if $number > 0 && $number < 15?
I tried with:
<?php
$number = rand("0","100");
switch($number) {
case: $number > 0 && $number < 15;
$output = 1;
break;
case: $number > 15 && $number < 50;
$output = 2;
break;
}
return $output;
?>
Try the following. Your colons were in the wrong place!
<?php
$number = rand("0", "100");
switch(true) {
case $number > 0 && $number < 15:
$output = 1;
break;
case $number > 15 && $number < 50:
$output = 2;
break;
}
?>
From the comment by DaveRandom below. Be aware that nothing will happen if $number is equal to 15. I would recommend changing one of your switch statements. Perhaps by changing your first case into:
case $number > 0 && $number <= 15:

strange beahviour with a php switch?

A sample of what I'm trying to do will be more explicit:
var_dump($opti_point); //int 0
if ($opti_point>=0 && $opti_point < 25) echo 'good';//echoing good
switch ($opti_point) {
case ($opti_point>= 0 && $opti_point < 25):
$test = 0;
break;
case ($opti_point >= 25 && $opti_point < 50):
echo 'we are in this case'; // This case is called !
$test = 2;
break;
default:
test = 0;
break;
}
Is there a trick here ?
thx
You cannot put comparisons inside "case" unfortunately...
A switch is only used when a value can have one of a limited number of values like so:
switch ( $val ) {
case 1:
echo "Got 1";
break;
case 2:
echo "Got 2";
break;
default:
echo "Got invalid value";
}
A workaround would be to use:
switch (true) {
case ($opti_point>= 0 && $opti_point < 25):
$test = 0;
break;
case ($opti_point >= 25 && $opti_point < 50):
echo 'we are in this case';
$test = 2;
break;
default:
test = 0;
break;
}
Which will work, but is a bit ugly...
Also, you're missing a single quote in echo we are in this case'; which should be echo 'we are in this case';
You should be using an if instead =)
You need to change the switch argument to true of false if you do comparison liek that in the cases.
You are not comparing what you think you are comparing. This is the code I think you want.
var_dump($opti_point); //int 0
if ($opti_point>=0 && $opti_point < 25) {
$test = 0;
echo 'You are now here!';
} elseif ($opti_point >= 25 && $opti_point < 50) {
$test = 2;
} else {
test = 0;
}
In your example, you are comparing the result of the logical statement...
($opti_point>=0 && $opti_point < 25) // true
To the value of $opti_point
0 // false
So PHP is actually converting what you think in an integer into a boolean to compare it with the result of the conditional statement.
I think that's a very bad way to use a switch statement, you should not put conditional sentences in the cases... In fact, I'm sure that that would be illegal in other languages and I'm not sure that it should work in PHP. Use a number of concatenated if-else conditions instead:
if ($i == 0) {
echo "i equals 0";
} elseif ($i == 1) {
echo "i equals 1";
} elseif ($i == 2) {
echo "i equals 2";
}
I'll go true the code with you
var_dump($opti_point); //int 0 , or false --- you should use TRUE
if ($opti_point>=0 && $opti_point < 25) echo 'good';//echoing good
switch ($opti_point) { // chose the case that is $opti_point (0 or false)
case ($opti_point>= 0 && $opti_point < 25): // true, so go to next
$test = 0;
break;
case ($opti_point >= 25 && $opti_point < 50): //false si this is the wan I pick
echo 'we are in this case'; // This case is called !
$test = 2;
break; // ingore the rest
default:
test = 0;
break;
}
you should use TRUE in the switch
if this is the exact code then try this
var_dump($opti_point); //int 0
if ($opti_point>=0 && $opti_point < 25) echo 'good';//echoing good
switch ($opti_point) {
case ($opti_point>= 0 && $opti_point < 25):
$test = 0;
break;
case ($opti_point >= 25 && $opti_point < 50):
echo 'we are in this case'; // This case is called !
$test = 2;
break;
default:
$test = 0;
break;
}
You have a misunderstanding on how switch-case works. Case DOES NOT TEST YOUR EXPRESSION TO BE boolean TRUE!
It compares its value to 'switch' value!
Here is an explanation:
$opti_point>= 0 && $opti_point < 25 evalutes to true which integer representation is 1 and since PHP can deal with types on it's own, it turnes true to 1 and compares it with value in switch which is 0
$opti_point >= 25 && $opti_point < 50 evaluates to false which is 0 as integer, so... that's your case ;)

Categories