Steve Price
Steve Price

Reputation: 600

finding the lowest value integer from data stored in an array using php

I have an array called $quotes and when I print_r an example of the results are like this:

Array ( [id] => advshipper [methods] => Array ( 
[0] => Array ( [id] => 2-0-0 [title] => Small Parcels [cost] => 4.5 [icon] => [shipping_ts] => [quote_i] => 0 ) 
[1] => Array ( [id] => 3-0-0 [title] => Large Parcels up to 1150mm long [cost] => 8.95 [icon] => [shipping_ts] => [quote_i] => 1 ) 
[2] => Array ( [id] => 4-0-0 [title] => Extra Large Parcels over 1150mm long [cost] => 15 [icon] => [shipping_ts] => [quote_i] => 2 ) ) [module] => Shipping )

What I need is a simple way to look at $quotes, find which [cost] has the lowest value and then record, in this example, the [0] so that they can be used in another code segment.

Short of exploding the array and then looping through all the content, is there a simple method to achieve what I want?

Upvotes: 0

Views: 58

Answers (3)

Mojtaba
Mojtaba

Reputation: 5002

As you are using the version higher than 5.5, you can simply use array_column function:

echo min(array_column($quotes['id'],'cost'));

And if you want, you can retrieve the id of the row as well:

echo min(array_column($quotes['id'], 'cost', 'id'));

Upvotes: 1

user6202450
user6202450

Reputation:

If I understood that correctly, you need to find the lowest value for cost array. You can do an array_map to get the values

$lowestcost = array_map(function($costval) {
return $costval['cost'];
}, $array);

Then you need to use

min($lowestcost)

Hope this helps

Upvotes: 0

Bartosz Zasada
Bartosz Zasada

Reputation: 3900

array_reduce($quotes, function($minimum, $current) {
    return $current['cost'] < $minimum['cost'] ? $current : $minimum;
}, $quotes[0]);

This will return the row of $quotes that has the lowest value of cost.

Upvotes: 0

Related Questions