Robert Cooper Robert Cooper - 1 year ago 84
PHP Question

Finding the lowest number in an array but skipping zero

Can someone help me re-write this:

public function allOutOfStockShows()

$out_of_stock_shows = 999;

foreach ($this->variants as $variant){

if (!$variant->out_of_stock_shows) { continue; }

if ($variant->out_of_stock_shows < $out_of_stock_shows) { $out_of_stock_shows = $variant->out_of_stock_shows; }


if ($out_of_stock_shows == 999) { return 'Out Of Stock'; }

return config('site.out_of_stock_shows')[$out_of_stock_shows]; // eg '2-3 days','3-5 days'

The values for the (integer) $variant->out_of_stock_shows can range from 0-12 so I start the 'highest' number as being a number I plucked out of the air - 999 - and then I shoot for a lower value as you can see. It works but feels wrong, how should I be approaching this?

Answer Source

Maybe if you convert to array and use min() function;

$out_of_stock_shows = array_map( 
    function( $item ) { 
        return $item->out_of_stock_shows; 
    }, $this->variants );

$out_of_stock_shows = min( array_filter( $out_of_stock_shows ) );
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download