Search code examples
phpboolean-logic

Execute all functions in a logical operation


I have two functions a() and b(), both return a Boolean. I know that evaluation of logical expressions is stopped as soon as the result is known, but is there a way to perform a logical operation on two or more functions in such a manner that both functions execute?


Solution

  • According to this comment on the PHP manual

    Evaluation of logical expressions is stopped as soon as the result is known. If you don't want this, you can replace the and-operator by min() and the or-operator by max().

    So this code may be of use to you, as you can see all functions are called in each case and, yes, you can use this with more than two functions:-

    function a()
    {
        echo "function a<br/>\n";
        return true;
    }
    function b()
    {
        echo "function b<br/>\n";
        return false;
    }
    
    function c()
    {
        echo "function c<br/>\n";
        return false;
    }
    
    echo min(a(), b(), c());
    echo "<br/>";
    echo max(a(), b(), c());
    echo "<br/>";
    

    Output:-

    function a
    function b
    function c
    (false)    
    function a
    function b
    function c
    (true)
    

    Demo