Junaid Rehman
Junaid Rehman

Reputation: 71

How to get array with maximum value within array in php

I have an array which looks like this:-


    $my_array = array();
    $my_array[] = array("is_match" => false, "number_of_matches" => 0);
    $my_array[] = array("is_match" => true, "number_of_matches" => 2, "id" => 1);
    $my_array[] = array("is_match" => false, "number_of_matches" => 5, "id" => 1);
    $my_array[] = array("is_match" => false, "number_of_matches" => 3, "id" => 1);
    $my_array[] = array("is_match" => false, "number_of_matches" => 1, "id" => 1);
    

Now i want to get the array with maximum number of matches i.e number_of_matches. Like in this example i want to get below array


    array("is_match" => false, "number_of_matches" => 5, "id" => 1);
    

I know max() function but it returns maximum value in the array but i want to return the array containing the maximum value in number_of_mataches

Upvotes: 1

Views: 86

Answers (3)

user1846065
user1846065

Reputation:

You can use uasort:

function cmp($a, $b) {
    if ($a['number_of_matches'] == $b['number_of_matches']) {
        return 0;
    }
    return ($a['number_of_matches'] < $b['number_of_matches']) ? 1 : -1;
}

uasort($my_array, 'cmp');

echo $my_array[0]['number_of_matches'];

$my_array[0] will hold the array with the highest number_of_matches

Upvotes: 1

sjagr
sjagr

Reputation: 16502

If you truly just want the maximum number_of_matches element, then I think uasort is a bit overkill and may potentially take longer to execute (however negligible that difference could be.)

$max = false;
foreach ($my_array as $a) {
    if (!$max || $max['number_of_matches'] < $a['number_of_matches']) {
        $max = $a;
    }
}

Only limitation with this is that it will return the first maximum and no other. To get around that limitation (and this gets lengthier than a uasort but may still be faster than a sort):

$max = false;
foreach ($my_array as $a) {
    if (!$max || $max['number_of_matches'] < $a['number_of_matches']) {
        $max = $a;
        $max_array = array();
        $max_array[] = $a;
    } else if ($max['number_of_matches'] == $a['number_of_matches']) {
        $max_array[] = $a;
    }
}

Upvotes: 1

Milasinovic
Milasinovic

Reputation: 36

You can achieve this with:

usort($my_array, function($a, $b) {
    return $b['number_of_matches'] - $a['number_of_matches'];
});

Upvotes: 1

Related Questions