0
$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?

6
  • 1
    Easiest way to start debugging is to echo $age before your switch statement and see what that variable is Commented Jan 28, 2023 at 18:29
  • @KosyOnyenso I've already done that. It's 0 and it should echo 'Congrats.. etc' Commented Jan 28, 2023 at 18:32
  • 2
    There's a syntax error in this code, not sure how you're getting any output. Commented Jan 28, 2023 at 18:32
  • @frengo- please try the answer I just gave Commented Jan 28, 2023 at 18:34
  • 1
    Assuming the quote syntax error is a typo (and fixed), then as to why when $age == 0 falls into the case $age < 0 it is due to loose comparisons between 0 and false which the switch statement employs. Commented Jan 28, 2023 at 18:59

2 Answers 2

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;
}
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.