skip to Main Content
$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?

2

Answers


  1. 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;
    }
    
    Login or Signup to reply.
  2. 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';
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search