PHP如果块仅使用最后一个块

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.

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

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;
}

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:
}