0

I am facing one issue for getting the highest value from array. I have two arrays. First array is below:

$catids = [239,240,238]

Second array is multidimensional array below:

 $categories = Array
 (
[0] => Array
 (
 [category_id] => 239
 [final_price] => 1999
 )
[1] => Array
 (
 [category_id] => 238
 [final_price] => 2990
 )
[2] => Array
 (
 [category_id] => 240
 [final_price] => 3500
 )
[3] => Array
 (
 [category_id] => 241
 [final_price] => 500
 )
)

Expected Out

Array
(
[category_id] => 240
[final_price] => 3500
)

In my input array catid 240 is having heighest value 3500.

What I've tried

I have sorted the array by final_price in ascending order
usort($categories, function($a, $b) {
 return $a['final_price'] <=> $b['final_price'];
 });
Hamid Ali
8851 gold badge8 silver badges22 bronze badges
asked Jun 29, 2020 at 10:05
3
  • Does the $categories array come from a database? Commented Jun 29, 2020 at 10:13
  • @Michel yes its dyanmic Commented Jun 29, 2020 at 10:14
  • 3
    In that case, write a simple query to retrieve the highest value WHERE category_id IN (239,240,238). No need to loop any array. Commented Jun 29, 2020 at 10:16

1 Answer 1

2

Doing this in PHP is simple enough, you could just loop through the categories and check first that the category_id is in the array of category id's you are interested in, then compare the final_price against the current maximum...

$max = ["final_price" => PHP_INT_MIN];
foreach ( $categories as $category ) {
 if ( in_array($category["category_id"], $catids)
 && $category["final_price"] > $max["final_price"] ) {
 $max = $category;
 }
}
print_r($max);

which with the test data gives...

Array
(
 [category_id] => 240
 [final_price] => 3500
)
answered Jun 29, 2020 at 10:15
2
  • thanks its works can you tell me the menaing of this PHP_INT_MIN? Commented Jun 29, 2020 at 10:20
  • PHP_INT_MIN is just the lowest integer value, this should ensure that any value compared against it will be greater than it is. Commented Jun 29, 2020 at 10:21

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.