skip to Main Content

For example in the following code…

$a=1;
if($a == 1)
echo 'good'...

else
echo 'bad'...

if $a not equal 1, it will go to else, but…

$a=1;
$b=2;
if($a == 1)
echo 'good'...

elseif($b==2)
echo 'bad'...

The elseif only evaluates if $b is equal to 2, or it also too evaluates that $a is different from 1 as if elseif were an else?

In other words… Does elseif only check the condition that is put in it or does it also put the one that is not fulfilled in the if?

2

Answers


  1. The elseif statement in PHP only checks the condition that is specified within it. It does not automatically include the condition from the preceding if statement.

    In your example, if $a is equal to 1, the first if statement will be true, and it will execute the code block inside the if statement, which will output ‘good’. The elseif statement will not be evaluated in this case.

    If $a is not equal to 1, the first if statement will be false, and it will skip the code block inside the if statement. Then, the elseif statement will be evaluated. If $b is equal to 2, the elseif condition will be true, and it will execute the code block inside the elseif statement, which will output ‘bad’.

    Login or Signup to reply.
  2. This:

    $a=1;
    $b=2;
    if($a == 1)
    echo 'good'...
    
    elseif($b==2)
    echo 'bad'...
    

    Is exactly the same as:

    $a=1;
    $b=2;
    if($a == 1) {
       echo 'good'...
    }
    else {
       if($b==2) {
          echo 'bad'...
       }
    }
    

    Writing it like that makes the nesting more clear.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search