Reversing logic in condition



  • Let's say there's a function.

    function foo($a, $b, $reverse = false) {
        if ($a > $b) return $a - $b;
        else return $a + $b;
    }
    

    We need to make sure, $reverse == truethe result of the logical operation was provided that it was, in lieu of ($a > $b) It's gone. !($a > $b)♪ This operation needs to be introduced.



  • Special for cases like yours, there is an operator. https://ru.wikipedia.org/wiki/%D0%A1%D0%BB%D0%BE%D0%B6%D0%B5%D0%BD%D0%B8%D0%B5_%D0%BF%D0%BE_%D0%BC%D0%BE%D0%B4%D1%83%D0%BB%D1%8E_2 known as Excluding "or"

    The result of the operation is true at that time and only then, When only one of the arguments is true.

    In your case, it's very simple:

    if ($a > $b ^ $reverse) return $a - $b;
    else return $a + $b;
    

Log in to reply
 


Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2