Kyle Blue Kyle Blue -4 years ago 96
PHP Question

PHP - switch statement, without breaks in every case

This has got me stumped for a while now...
I was taught switch statements in PHP only use the "break" keyword in order to break the circuit of the switch statement.
Instead of using multiple if statements, to keep things clean, I used a switch statement (to validate a username/password)
This is the code.

Code:

switch(true){

case($passwords[$key] != $password):
echo "The username and/or password is incorrect<br>";
case(strlen($username) < 4 || strlen($username) > 10):
echo "The username must be between 4-10 characters<br>";
case(strlen($password) < 4):
echo "The password must be at least 4 characters<br>";
case(1>2):
echo $username . " " . $password . " " . strlen($username) . " " . strlen($password);
break;

default:
echo "Login Success<br>";
}


If I inputted:
Username: Kyle
Password: foobar

I would expect ONLY the output "The username and/or password is incorrect
" as this is the only true condition...
However, everything up until break seems to evaluate as true, outputting everything but the default, even though (1>2) is clearly false...

Help is greatly appreciated.
Thanks!

Answer Source

You have to add a break in every case:

case($passwords[$key] != $password):
        echo "The username and/or password is incorrect<br>";
        break;
    case(strlen($username) < 4 || strlen($username) > 10):
        echo "The username must be between 4-10 characters<br>";
        break;
    case(strlen($password) < 4):
        echo "The password must be at least 4 characters<br>";
        break;            
    case(1>2):
        echo $username . " " . $password . " " . strlen($username) . " " . strlen($password);
        break;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download