0

I have code that looks like this:

if ($first == 1); {
$q1 = "1";
$q2 = "2";
$q3 = "3";
}

if ($first == 2); {
$q1 = "1a";
$q2 = "2a";
$q3 = "3a";
}

if ($first == 3); {
$q1 = "1b";
$q2 = "2b";
$q3 = "3b";
}

The variable $first comes out of an array that was sorted earlier. It's a key value from that array.

In this case, the variable is 2, yet the code -always- takes the last block regardless of anything else. So it would report the answers for the 3 block, not the 2 block.

That is to say, getting a value of 1, 2 or 3 for $first will always return 1b for $q1.

Anyone know why? this is making me go insane.

Inter Node
  • 11
  • 2

3 Answers3

4

First, remove the semicolons from the brackets surrounding your conditions.

Secondly, you should use if() and else if():

if($first == 1) {
    $q1 = "1";
    $q2 = "2";
    $q3 = "3";
} else if($first == 2) {
    $q1 = "1a";
    $q2 = "2a";
    $q3 = "3a";
} else if($first == 3) {
    $q1 = "1b";
    $q2 = "2b";
    $q3 = "3b";
}

If you're comparing more than 3 states, however, you should use a switch() statement to produce cleaner code, like this:

switch($first) {
    case 1:
        $q1 = "1";
        $q2 = "2";
        $q3 = "3";
    break;
    case 2:
        $q1 = "1a";
        $q2 = "2a";
        $q3 = "3a";
    break;
    case 3:
        $q1 = "1b";
        $q2 = "2b";
        $q3 = "3b";
    break;
}
Bojangles
  • 99,427
  • 50
  • 170
  • 208
  • 1
    Or just use a switch statement. – C0deH4cker Jun 02 '12 at 22:07
  • @C0deH4cker In this case, using an `if()` is fine. A `switch()` would incur more lines of code, but I agree if more than 3 states are being tested, a switch is the best way to go. – Bojangles Jun 02 '12 at 22:10
  • I used to write a switch when I've got more than 2 states, that's clearer, even id there are a bit more line. But this is a personnal choice. – zessx Jun 02 '12 at 22:13
  • Boooo. :) The downside to using `switch` is that it's so easy to forget the `break` statements. For that reason, I prefer `if/else`. – Michael Jun 02 '12 at 22:32
2

You should not have ; on the end of your if statments. I.e change if ($first == 1); { to this if ($first == 1) {

secretformula
  • 6,414
  • 3
  • 33
  • 56
0

You also can use a switch statement :

switch($first) 
{
    case 1:
       $q1 = "1";
       $q2 = "2";
       $q3 = "3";
       break;
    case 2:
       $q1 = "1a";
       $q2 = "2a";
       $q3 = "3a";
       break;
    case 3:
       $q1 = "1b";
       $q2 = "2b";
       $q3 = "3b";
       break;
    default:
}
zessx
  • 68,042
  • 28
  • 135
  • 158