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

Control Flow: Switch Forum

View Course » View Exercise

586 points
51f5629252f86301b000822e_748113678
Submitted by
Furqan Arshad
over 4 years ago

Please help me clear this switch statement concept!!

<?php
$fruit = "Apple";

switch ($fruit) {
case 0:
echo "Apple";
break;
case 1: 
echo "Yummy";
break;

default:
echo 'the fruit is apple';
}

Here, this code will show anything added in case 0. I am confused switch statement selects (case 0:) or what we have defined earler, $fruit= apple:

If I change this Apple into anything under case 0: it will show that one and will only look for case 0:

I am confused. switch statement selects case ? echo ? or what ?


2 votes

permalink

The "case" is the IF.
case 0:
echo "Apple";
break;

is the same as: if ($fruit == 0) { echo "Apple!"); }. If you want to check for fruits, you would do it like this:

$fruit = "Apple";

switch ($fruit) {
    case "Apple":
        echo "The fruit is an apple";
        break;
    case "Banana": 
        echo "Bananas are yummy";
        break;
    default: 
        echo 'The fruit isnt a banan or an apple';
}

504 points
2b153953ef015ea1708bd5f306bd2bb6?s=140&d=retro
Submitted by
Roni
over 4 years ago

1 Comment

51f5629252f86301b000822e_748113678 Furqan Arshad over 4 years ago

Thanks a billion dear ! :) I understood the concept now. Thank you very very much. I was waiting for someone to answer and finally its you.