PHP switch语句“回显”错误的大小写

eqoofvh9  于 2023-01-29  发布在  PHP
关注(0)|答案(2)|浏览(154)
$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;
}

这是我第一堂PHP课的内容,如果我输入2023,语句“echoes”第一种情况,但是它应该echoes第二种情况,知道为什么会这样吗?

fdx2calv

fdx2calv1#

switch ($age)更改为switch (true)。尝试以下操作:

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

0md85ypi2#

case s是值,而不是要计算的表达式。看起来您打算使用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';
}

相关问题