Loop through products and return first product that matches criteria I am writing a function which loops through an array of products.  The function needs to return:


the ID of the first product that has an image and is in stock
if no products have an image and are in stock, then return the first product id that has an image
if no products have an image, then return the first product id that is in stock
if no products have an image, and no products are in stock, return the first product id


This is what I have written, and it is working as expected:

function loopThroughProducts($products)
{
    $firstId = $products[0]-&gt;id;

    foreach ($products as $product) {
        if ($product-&gt;hasImage &amp;&amp; $product-&gt;inStock) {
            $id = $product-&gt;id;
            return $id;
        }
        if ($product-&gt;hasImage &amp;&amp; empty($firstIdWithImage)) {
            $firstIdWithImage = $product-&gt;id;
        }
        if ($product-&gt;inStock &amp;&amp; empty($firstIdInStock)) {
            $firstIdInStock = $product-&gt;id;
        }
    }

    if (!empty($firstIdWithImage)) {
        return $firstIdWithImage;
    }
    if (!empty($firstIdInStock)) {
        return $firstIdInStock;
    }

    return $firstId;
}


Does anyone see a way that I can optimize this loop or simplify the logic?  I dislike using so many sequential if-statements in one function, and there are some minor violations to the DRY principle.
Clean, readable code. But why not use more of PHP's standard array functions? Use the array_search or in_array functions. Or -even more fancy- the array_filter function.