RoPeDa
RoPeDa

Reputation: 53

Find the lowest PHP array value (specific) and return lowest key

I have an array, $prices, which looks like this:

Array
(
    [0] => Array
        (
            [regprice] => 25.00
            [saleprice] => 17.00
        )

    [1] => Array
        (
            [regprice] => 
            [saleprice] => 19.00
        )

)

When using $lowest_index = array_keys($prices, min($prices));, $lowest_index returns 1, because for that index, the value [regprice] is not set.

I would like to get the index of the array where [saleprice] is the lowest. In my case, that would return 0.

Upvotes: 1

Views: 47

Answers (1)

Nick
Nick

Reputation: 147166

If there is always a value in saleprice, you can adapt your code using array_column to look at only the saleprice values:

$lowest_index = array_keys(array_column($prices, 'saleprice'), min(array_column($prices, 'saleprice')));

Demo on 3v4l.org

Upvotes: 4

Related Questions