Understanding the logic with 2 returns?

I came across a method today that has the following at the end of it:

return in_array($id, $arr[0]) && in_array($this->id, $arr[1]);

Now help me understand this… That line basically says, “return TRUE if BOTH in_array functions return TRUE,” correct? Otherwise, I’m assuming it would return FALSE because no other return statements exist in the method.

Is the form that’s used here done a lot? I’ve never seen it done this way… Usually, you only see a singular return statement.

Hi,

Yeah you’re right about what it does. As long as the expression after the return statement only evaluates to a single value then PHP won’t have a problem with it.

in_array returns a boolean – true if the element is in in the array, false if it’s not
expression && expression “returns” (or evaluates to) a boolean – true if both expressions are true, false if either or both expressions are false

So in total the function returns a boolean – true if both elements are in their respective arrays, or false if either or both elements aren’t in their respective arrays.

This form isn’t used a whole lot, but you do see it every once in a while.

Another thing I’m reminded off by looking at this is that the following also confuses people a lot


class Something
{
    public $somevar;
    
    public function foo()
    {
        return $this->somevar = 5;
    }
}

Which

  • returns 5, AND
  • sets $this->somevar to 5

at the same time (compare to if (($pos = strpos($haystack, $needle)) !== false) which can be similarly confusing)

For a complete list of logical operators like && see http://php.net/manual/en/language.operators.logical.php

for readability, i’d have wrapped it in a set of parenthesis (just to avoid potential confusion of precedence; does it evaluate as (return function1()) && function2() or return (function1() && function2()) ), but yeah…