Efficient method to look for an instance of an object in a collection I'm trying to determine if an instance of an object exists within a collection.

I'm using array_walk_recursive to walk and check the leaves of an array.

I've added a small short circuit, but still all leaves will be iterated over.

I could alternatively use something like an exception which is thrown on the first find, to break out early, but that feels kind of wrong.

Am I missing a simple alternative?

&lt;?php

class Fish {}
class Mammal {}
class Whale extends Mammal {}
class Human extends Mammal {}
class Shark extends Fish {}

function anyFish(array $collection)
{
    $found = false;
    array_walk_recursive($collection, function ($v) use (&amp;$found) {
        if(!$found &amp;&amp; $v instanceof Fish)
            $found = true;
    });

    return $found;
}

$seas = [
    'pacific'  =&gt; [new Whale, new Shark],
    'atlantic' =&gt; [new Human, new Shark]
];

$pub = [new Human, new Human];

var_dump(anyFish($seas));
var_dump(anyFish($pub));


Output:

bool(true)
bool(false)


Found on Stackoverflow: https://stackoverflow.com/questions/17853113/break-array-walk-from-anonymous-function)
I think good coding practices should prioritize efficiency before code brevity.  It is important to not ask for unnecessary work to be done (this is part of the artistry of being a clever coder).  Implementing an early exit, in my opinion is a non-negotiable factor in selecting the "best" code design.

Using a function like array_walk_recursive() is handy for its leafnode traversal, but I agree that the syntax of making an early exit is a little unsightly.  For this reason, I recommend a language construct as part of the recursive design.  The conditional logic is the only part that can be condensed, so I've tried to boil it down as much as possible.

Code: (Demo)

function anyFish(array $collection)
{
    foreach ($collection as $item)
    {
        if((is_array($item) &amp;&amp; anyFish($item)) || $item instanceof Fish)
        {
            return true;
        }
    }
    return false;
}


I don't think it is horrible to look at, but everybody loves their own babies.  I'm not sure that I can make it any more readable.