I have the following function that works properly, except for when you use the input value of 0. I tried searching around to see if the 0 is equated as a NULL or if I’m doing something wrong.
When a zero is input, it outputs advanced which is greater than 20. Can anyone explain? Thanks
I plan on making the switch equate 0-10, 11-20, 21-30, 31-40, 41+ but for this example i am just using two scenarios. Thanks
**EDIT I do want values when its 20 🙂
function strengthPlan( $data ) {
$data = ( int ) $data;
switch( $data ) {
case( $data <= 19 ):
$result = 'standard strength';
break;
case( $data >= 20 ):
$result = 'advanced strength';
break;
}
return $result;
}
echo strengthPlan( 0 );
Your logic is incorrect. Switch statements are checking for equality. Your code is checking whether
$datais equal toTRUEorFALSE.will evaluate to:
because
0 < 20.Since
0is not equal toTRUEbut toFALSE(after conversion), the second case is run.Basically, you cannot use
switch casefor<or>but only for==.