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'];
    });
3
  • Does the $categories array come from a database?
    – Michel
    Commented Jun 29, 2020 at 10:13
  • @Michel yes its dyanmic
    – user
    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.
    – Michel
    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
)
2
  • thanks its works can you tell me the menaing of this PHP_INT_MIN?
    – user
    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.
    – Nigel Ren
    Commented Jun 29, 2020 at 10:21

Not the answer you're looking for? Browse other questions tagged or ask your own question.