Is there a way to break in If?

Asked

Viewed 426 times

9

I was wondering if there’s some kind of break on IF. My doubt is based on the example below. When the function b() returns false all following comparisons are not performed. I thought the condition would compare all values and return the result.

I may be talking nonsense, but it seems that launches a 'break' right when it finds a result that does not exceed the condition, something like a throw.


$a = function(){ echo 'a'; return 1; };
$b = function(){ echo 'b'; return 1; };
$c = function(){ echo 'c'; return 1; };

if( $a() && $b() && $c() )
echo 'sucesso';

output : a b c sucesso


$a = function(){ echo 'a'; return 1; };
$b = function(){ echo 'b'; return 0; };
$c = function(){ echo 'c'; return 1; };

if( $a() && $b() && $c() )
echo 'sucesso';

output : a b


My case was to use one if where the third condition depended on the other two as true, saving if + if. In the example above it worked as expected, but it was really new for me.

  • 2

    I’ve also noticed this in C# for example when I want to compare the property of an object, and this object is null, C# launches a exception, for this I compare before, in the same if(objeto != null && objeto.propriedade == valor), does not occur to exception, @bigown’s response helped me clear this up as well

  • 2

    @Marcogiovanni this is purposeful even to solve this kind of question. Without the Circuit short the code would have to be complicated.

2 answers

11


There’s something called short-Circuit. Relational operators operate this way. They evaluate until they are sure of the result. When the other operands can no longer alter the result no matter their values he no longer tries to evaluate anything and makes the decision.

This is useful because it gives better performance and avoids possible side effects that should eventually be avoided even depending on the previous condition. So:

if ( $a() && $b() && $c() ) fazAlgo;

Is the same as:

if ( $a() )
    if ( $b() )
        if ( $c() )
            fazAlgo;

That is, if you don’t get into the first one if will not get into the others. So it becomes easier to see. And interestingly enough programmer writes the second example without realizing that he could write in a single line.

Like the AND requires that all operating be true to result in true when a false tense is impossible for others to reverse the situation, has no reason to evaluate others.

The same can happen with OR. Only in this case the situation is different. This operator requires only one operand to be true for the final result to be true. If the first comes true, he will no longer look at the others:

if( $a() || $b() || $c() ) fazAlgo;

Is the same as:

if ( $a() ) fazAlgo;
else if ( $b() ) fazAlgo; //faz algo igual
else if ( $c() ) fazAlgo; //tem que ser igual

I put in the Github for future reference.

Just the $a() give away true and $b() and $c() nor will they be executed. If he gives false of course it will evaluate $b(), then the decision will be evaluated $c() depends on the outcome of it.

This can be observed with other relational operators (at least in some languages).

There’s language that doesn’t embrace it.

The bit operators (eg.: &, |) do not have the feature of closing the circuit and all perform always. Even they are used when the feature is not desired.

There is a question with a classic example of its use. You have a first operand that checks if a condition is met. The second operand will cause it to work correctly only if the first one is true. Typical of checking an object is null before accessing it.

  • I really did not know this. Very enlightening example. Thanks Big

  • Following the example of or, would be something like if( ($a() or $b()) && $c() ), $to or $b as true and $c as true. Correct?

  • 1

    If I understood, yes. In this case there are two expressions. The first will be true if one of the two operands is true, no matter which. So if $a()der verdadeiro, nem vai olhar$b(). E por consequência vai olhar $c()para ter certeza que o resultado final será verdadeiro. Se$to()der falso, vai olhar$b(). Se este der falso tb, nem vai olhar $c()`, it is already guaranteed to give false.

  • 1

    That’s right... Send this reply to the PHP DOC :)

  • 1

    @Papacharlie If you see what a minified code looks like, you’ll see that there are many if($var1 == true && $var2 = explode(' ', $var3) && $var4 = $var2[1])

  • 1

    @Guilhermelautert is this minified? nor do I want to see the non-manified :)

  • @bigown kkk, truth would be $a, $b, $c, and == 1

Show 2 more comments

1

Yes, the argument passed on break you go out of a level. If you have a foreach and an if:

foreach ( $var as $key )
{
  if ( $key == 0 )
  {
    #code...
    break(2);
  }
}

This way vc interrupts also the foreach. The way you passed in the example could be used as alternative

switch (variable) {
    case 'value':
        # code...
        break;

    default:
        # code...
        break;
}
  • 1

    I don’t think that would be the question. I know there is break loop and switch. The question is IF.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.