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

Control Flow: Switch Forum

View Course » View Exercise

576 points
526ee2d180ff33fe280002fb_903789625
Submitted by
Barbara Cernosa
about 3 years ago

Why does the console return '$i is 0.', when I set $i = "random string"?

Why does the console return '$i is 0.', when I set $i = "random string"?

<?php
$i = "random string";

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

2 votes

permalink

In this code, the switch syntax is checking for values (case 0, case 1, case 2, etc)
Since strings don't have values unless you assign them values, the computer immediately assigned $i as the first case it saw. It did not go to default because the rest of the cases are all values. It basically said: "$i is not case 0 nor case 1, etc... No strings for $i available, default doesn't satisfy syntax. $i is case 0."

The syntax is saying that if $i is a *value* it would go through the switch normally, if it was not it would head over to the default. But none of these are strings so the computer "malfunctioned." You confused the computer!

If you wanted the program to check for strings, you would put:
case "string goes here"
echo //some code;
break;

Which is basically:
if ($i=="string goes here"){
//some more code
}

If you put this into the program:
<?php
$i = "random string";
switch ($i) {
case "random string":
echo '$i is 0.';
break;
case 1:
case 2:
echo '$i is either 1 or 2.';
break;
case 3:
case 4:
echo '$i is either 3 or 4.';
break;
case 5:
case 6:
case 7:
echo '$i is somewhere between 5 and 7.';
break;
default:
echo "I don't know how much \$i is.";
}
?>

It would successfully read $i as "random string" and echo: $i is 0.
You would be able to put case "random string" in any of the syntax's and it would work.

If my explanation wasn't enough, head over to: http://www.php.net/manual/en/control-structures.switch.php which has a better explanation!

422 points
5389f03352f8635be40029d0_546373091
Submitted by
Konoha7_51d1865d52f8639db80176d5_del
about 3 years ago