PHP - Does if/elseif behave like stacked if statements?

Does if/elseif behave like stacked if statements?

if( $a == 2 )
{
   $a = 0;
   $b = 2;
}
elseif( $b == 2 )
{
   echo "Cool?";
}

Answers


On the basis that the else is there, no, it won't work.

For it to work how you wish it to, you'd need to remove the else and just use 2 if statements, such as;

// Set default values;
$a = 2;
$b = 0;

// Check $a
if( $a == 2 )
{
    // Change values
    $a = 0;
    $ b = 2;
}

// Check $b, which is now 2 due to the condition matching above
if( $b == 2 )
{
   echo "Cool?";
}

I believe you're slightly missing the point with the else.

It is used for condition matching, to confirm multiple possibilies.

For example, let's imagine a lottery, where the prize money is split into ranges;

Numbers 01 - 10 = $5. Numbers 11 - 20 = $10. Numbers 21 - 30 = $20.

You're code could look something like

<?php
$random_result = mt_rand(0, 30);

if ($random_number > 20) {
    $amount = 20;
}
else if ($random_number > 10) {
    $amount = 10;
}
else
{
    $amount = 5;
}
echo 'The jackpot for today was $' . $amount . '!';

No, if $a is 2 when the if checks, the elseif will not be checked. You should consider the entire if...elseif section a single statement where the first condition that evaluates as true stops the rest from being checked.

If the elseif were a separate if, then yes, it would output Cool?.

But it's not.

So it won't.


The elseif portion of your code will not execute if any if/elseif... prior to it are true. The if/elseif/... blocks execute in order, and once one of them is true, the others are not considered.


Need Your Help

VBA Subscript out of range on selection

excel vba excel-vba

I have 2 values in sheet1 which I want to migrate to sheet2. As of now my my CommandButton works fine till the point I create a newsheet. But as soon as I select my newsheet it gives me a subscript...