Home > Software engineering >  PHP switch statement "echoing" the wrong case
PHP switch statement "echoing" the wrong case

Time:01-29

$year = readline('Type your year of birth: ');

$age = 2023 - $year;

switch ($age) {
    case ($age < 0):
    echo 'I don't see in the future.';
    break;
    case ($age >= 0) && ($age <= 3):
    echo 'Congrats. A newborn capable of using the PC.';
    break;
    case ($age > 3):
    echo 'Our system calculated that you are:' . ' ' . $age . ' ' . 'years old';
    break;
}

So this is from my first lesson of PHP and the statement "echoes" the first case if I input 2023 but it should echo the second one. Any idea why this happens?

CodePudding user response:

Change the switch ($age) to switch (true). Try this:

switch (true) {
    case ($age < 0):
    echo "I don't see in the future.";
    break;
    case ($age >= 0) && ($age <= 3):
    echo "Congrats. A newborn capable of using the PC.";
    break;
    case ($age > 3):
    echo "Our system calculated that you are:" . " " . $age . " " . "years old";
    break;
    default:
    break;
}

CodePudding user response:

cases are values, not expressions to evaluate. It looks like you meant to use an if-else:

if ($age < 0) {
    echo 'I don\'t see in the future.';
} elseif ($age >= 0) && ($age <= 3) {
    echo 'Congrats. A newborn capable of using the PC.';
} else if ($age > 3) { # Could have also been an "else", without the condition
    echo 'Our system calculated that you are:' . ' ' . $age . ' ' . 'years old';
}
  • Related