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.

3 Answers 3

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;
}
Sign up to request clarification or add additional context in comments.

4 Comments

Or just use a switch statement.
@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.
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.
Boooo. :) The downside to using switch is that it's so easy to forget the break statements. For that reason, I prefer if/else.
2

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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.