0

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?

4
  • Use array_filter with callback to handle your logic. Commented May 30, 2016 at 14:16
  • What is your php version? Commented May 30, 2016 at 14:24
  • So, you are lucky. check out my answer Commented May 30, 2016 at 14:35
  • @StevePrice, Could you find a solution? Commented May 31, 2016 at 13:52

3 Answers 3

1

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'));
Sign up to request clarification or add additional context in comments.

2 Comments

This returns a result of 1 in the given example. I'm assuming that relates to it being the first of the data sets in the array. It can't mean $quotes[1] because that is the second most expensive. Can I just manipulate the result of 1 to give me the correct $quotes[0] result I need?
@StevePrice, Yes. I updated the code. Actually, you can read the documentation of the function to use it in your own way. It's too easy and clear
0
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.

1 Comment

Can you explain your answer a little for me please? What would happen if $quotes[2] happened to be the cheapest option?
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.