Harry Harry - 6 months ago 12
PHP Question

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!

Answer

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;
    }

}