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 isin 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]->id;
foreach ($products as $product) {
if ($product->hasImage && $product->inStock) {
$id = $product->id;
return $id;
}
if ($product->hasImage && empty($firstIdWithImage)) {
$firstIdWithImage = $product->id;
}
if ($product->inStock && empty($firstIdInStock)) {
$firstIdInStock = $product->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.