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

Control Flow: Switch Forum

View Course » View Exercise

805 points
58e619647cd340ac9f79600c90532a0f?s=140&d=retro
Submitted by
wasabi991011
over 4 years ago

Why wont my code work?

ok so I have made a code that acts like a calculator but there are lots of errors all the time. This one I cant figure out:
Parse error: syntax error, unexpected T_STRING, expecting ',' or ';' on line 18

Here is my code:

<?php
$number1 = "60";
$number2 = "3";
$operation = "÷";
switch ($operation){
case 1: "+";
echo $number1 + $number2;
break;
case 2: "-";
echo $number1 - $number2;
break;
case 3: "÷";
echo $number1 ÷ $number2;
break;
case 4: "X"
echo $number1 X $number2;
break;
}
?>


1 vote

permalink

This is a bit beyond what this section teaches, but I went on compilr to fix your code and make it work. After running it a few times, it seems to work! See explanation at the bottom.

<?php
      $number1 = 60;
      $number2 = 3;
      $operation = "*";
        switch ($operation) {
           case "+":
                echo ($number1 + $number2);
                break;
           case "-":
                echo ($number1 - $number2);
                break;
           case "/":
                echo ($number1 / $number2);
                break;
           case "*":
                echo ($number1 * $number2);
                break;
        }
         ?>
  1. You treated the $number variables as strings. Since they are actual numbers, there is no need for the quotation marks.
  2. Your case formatting syntax was wrong. It should look like the word case followed by either the string that you specified or a number. Since we are trying to use the operation string, the case names are the arithmetic operations surrounded by quotations.
  3. To echo the result of the operations, you have to put them in parenthesis so the code can execute them.

Hopefully this helps! I changed the operation variable around but I saw it work with all the 4. If you have questions let me know. Cheers!

692 points
50c8aa845f1c4c93f200652a_924031435
Submitted by
excowboy
over 4 years ago

3 Comments

2b153953ef015ea1708bd5f306bd2bb6?s=140&d=retro Roni over 4 years ago

Actually, his code was "correct", but he was using ";" after the cases instead of ":".

50c8aa845f1c4c93f200652a_924031435 excowboy over 4 years ago

d'oh!!!

16549be8aab2ba368b3190967ab92f61?s=140&d=retro michaelruiter almost 3 years ago

This code dont help me i must have thrre breaks said the program?!!!