Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unusual use of && operator [duplicate]

Tags:

operators

php

I am trying to understand the below code but I am confused by the use of the && operator.
Please explain the purpose of the && operation in the following code

function getErrors($autoClean=TRUE) {
     $retVal = $this->getErrorMessages();
     $autoClean && $this->unsetErrorMessages();
     return $retVal;
}
like image 735
Code Junkie Avatar asked Aug 06 '15 05:08

Code Junkie


2 Answers

Here, && acts as a short-circuit operator (see also the code example here).

  • If $autoClean evaluates to true, $this->unsetErrorMessages() will be executed.
  • If $autoClean evaluates to false, $this->unsetErrorMessages() will not be executed.

Using || instead of && would reverse this behavior.

The same behavior can obviously also be achieved by adding an additional if statement. In doing so:

  • a && b() can be rewritten as

    if (a) {
        b();
    }
    
  • a || b() can be rewritten as

    if (!a) {
        b();
    }
    

While the use of short-circuit operators can reduce the number of lines, it can also make code harder to read.

In terms of execution speed, there should be no noticeable difference.


Update

I have to retract my earlier statement about there being no noticeable difference in execution speed. Given the following two test scripts, i.e. a version with the short-circuit operator:

<?php
    $a = true;                                                                                                   

    function b() { global $a; $a = !$a; }

    for ($i = 0; $i < 10000000; $i++) {
        $a && b();
    }
?>

And a version with an if statement:

<?php
    $a = true;                                                                                                   

    function b() { global $a; $a = !$a; }

    for ($i = 0; $i < 10000000; $i++) {
        if($a) { b(); }
    }
?>

It turns out that the second version (with the if statement) is roughly 40% faster (~450ms vs. ~750ms) on my PHP 5.5.9 version running on Ubuntu 14.04 LTS (64 bit).

Results may vary for different PHP versions and operating systems, but at least on my machine I consistently notice a significant difference in execution speed.

like image 139
Robby Cornelissen Avatar answered Sep 23 '22 06:09

Robby Cornelissen


Here, && acts as a short-circuit operator as told by @robby.

  • If you call getErrors(), $autoclean will be true, $this->unsetErrorMessages() will be executed.
  • If you call getErrors(false), $autoclean will be false, $this->unsetErrorMessages() will not be executed.

The line provides us a behaviour to prevent default execution of any code and also provides us facility to reduce lines of code as

$autoClean && $this->unsetErrorMessages();

will be equivalent to

if($autoClean){
   $this->unsetErrorMessages();
}
like image 25
Ashwani Shukla Avatar answered Sep 25 '22 06:09

Ashwani Shukla