GRowing
GRowing

Reputation: 4717

PHP IF Statement - Sectioning off multiple conditions

It seems inefficient to me to write multiple conditions to do the same action,,, for example

if ( (condition_one || (condition_two && condition_three) )
{
    // Do this ...
}
elseif ( condition_two && condition_three)
{
    // Do same as before ...
}
else
{
    // Do that ...
}

Would there be a valid approach to accomplishing this? Where condition_two and condition_three have to be executed together but separately from condition_one...

if ( (condition_one || (condition_two && condition_three) )
{
    // Do this ...
}
else
{
    // Do that ...
}

In other words,,, is there some way, that I am unaware of, to do this:

if ( ( $a < $b || ( $a <= $b && $c = $d ) )
{
    echo 'foo';
}
else
{
    echo 'bar';
}  

Rather than this:

if ( ( $a < $b )
{
    echo 'foo';
}
elseif ( $a <= $b && $c = $d )
{
    echo 'foo';
}
else
{
    echo 'bar';
}

Upvotes: 0

Views: 219

Answers (2)

nerdlyist
nerdlyist

Reputation: 2857

You can test this easy but you had an extra paren

<?php

function testNest($a, $b, $c, $d){
    if ($a < $b || ( $a <= $b && $c = $d )) {
        echo 'foo';
    } else {
        echo 'bar';
    }
}


testNest(3, 2, 3, 2); //bar
testNest(1, 2, 3, 2); //foo

function testElif($a, $b, $c, $d){
    if ($a < $b ){
        echo 'foo';
    } elseif ( $a <= $b && $c = $d ) {
        echo 'foo';
    } else {
        echo 'bar';
    }
}

testElif(3, 2, 3, 2); //bar
testElif(1, 2, 3, 2); //foo

I'll let you come up with more examples but there really is no need for elseif

Upvotes: 1

Louis Loudog Trottier
Louis Loudog Trottier

Reputation: 1387

You have an extra ( in your code above but another way you could do this is ti use what we call switch fallback: something like so:

switch(true){
case $a < $b: //fallback
case ( $a <= $b && $c = $d ):
   //do something
   break;

default:
  //default action
break;

}

Notice i skipped a 'break' for the fallback, so it will run if any of the 2 'Cases' is (true).

Upvotes: 0

Related Questions