This forum is now read-only. Please use our new forums at discuss.codecademy.com.

Control Flow: Switch Forum

View Course » View Exercise

650 points
515fd7ae5c3d5297280017f1_331281329
Submitted by
Heqing Wong
over 4 years ago

Why i can't run it?

<!DOCTYPE html>





<?php
$i = 5;

switch ($i) {
    case 0:
        echo '$i is 0.';
        break;
    case 1:
    case 2:
  if($i==3||
     $i==4||
     $i==5){echo '$i is somewhere between 1 and 5.';}
        break;
    case 6:
    case 7:
        echo '$1 is either 6 or 7.';
        break;
    default:
        echo "I don't know how much \$i is";
        break;
}
?>
</body>

who can help me?


9 votes

permalink

you have a too high error in your syntax, see my code of example! below:

<?php
$i = 5;

switch ($i) :
    case 0:
        echo '$i is 0.';
        break;
    case 1:
    case 2:
    case 3:
    case 4:
    case 5:
        echo '$i is somewhere between 1 and 5.';
        break;
    case 6:
    case 7:
        echo '$1 is either 6 or 7.';
        break;
    default:
        echo "I don't know how much \$i is";
        break;
endswitch;
?>

425 points
5138d98f09264a0dfc005d92_324158091
Submitted by
Sergio A
over 4 years ago

3 Comments

5143282795b467b5c3006e47_202960785 Kareem Damen over 4 years ago

thx!

515fd7ae5c3d5297280017f1_331281329 Heqing Wong over 4 years ago

I know this is right ,but i want to use the code that named "falling through"

Picture Dan Reinders over 4 years ago

In the code in this answer case 1, case 2, case 3, and case 4 all "Fall Through" to the code in case 5. At the end of the code in case 5 the break statement ends the execution of the switch statement for those cases.

case 6 falls through to case 7 and then the break ends the execution of the switch statement for those cases.


0 votes

permalink

It doesnt work because $i == 5. And you don't have case 5: in your code.

You only have case 2 and then your code skips to the situation when $i == 6

And what are you trying to acomplish with that code? Translated into english it would be like:

$i is 2
if $i is 2 chek if $i is either 3, 4, 5 and, if it isn't, do nothing!

It is obvious that, as long as $i == 2, it can't simoultaneusly be 3, 4 or 5.

174 points
Picture
Submitted by
Andrei Ionita
over 4 years ago


0 votes

permalink

switch ($i) {
case 0:
echo '$i is 0.';
break;
case 1:
case 2:
case 3:
case 4:
case 5:
echo '$i is somewhere between 1 and 5.';
break;

1228 points
52f07fbc548c358e90000e1a_385034243
Submitted by
carlosmante
over 4 years ago