Home » Php » php – Find highest value in multidimensional array

php – Find highest value in multidimensional array

Posted by: admin April 23, 2020 Leave a comment

Questions:

The Problem

I have a multidimensional array similar to the one below. What I’m trying to achieve is a way to find and retrieve from the array the one with the highest “Total” value, now I know there’s a function called max but that doesn’t work with a multidimensional array like this.

What I’ve thought about doing is creating a foreach loop and building a new array with only the totals, then using max to find the max value, which would work, the only issue would then be retrieving the rest of the data which relates to that max value. I’m not sure that’s the most efficient way either.

Any ideas?

Array
(
    [0] => Array
        (
            [Key1] => Key1
            [Total] => 13
        )

    [1] => Array
        (
            [Key2] => Key2
            [Total] => 117
        )

    [2] => Array
        (
            [Key3] => Key3
            [Total] => 39
        )
)
How to&Answers:

Since PHP 5.5 you can use array_column to get an array of values for specific key, and max it.

max(array_column($array, 'Total'))

Answer:

Just do a simple loop and compare values or use array_reduce

$data = array_reduce($data, function ($a, $b) {
    return @$a['Total'] > $b['Total'] ? $a : $b ;
});

print_r($data);

See Live Demo

Answer:

It’s so basic algorithm.

$max = -9999999; //will hold max val
$found_item = null; //will hold item with max val;

foreach($arr as $k=>$v)
{
    if($v['Total']>$max)
    {
       $max = $v['Total'];
       $found_item = $v;
    }
}

echo "max value is $max";
print_r($found_item);

Working demo

Answer:

I know this question is old, but I’m providing the following answer in response to another question that pointed here after being marked as a duplicate. This is another alternative I don’t see mentioned in the current answers.

I know there’s a function called max but that doesn’t work with a multidimensional array like this.

You can get around that with array_column which makes getting the maximum value very easy:

$arr = [['message_id' => 1,
             'points' => 3],
        ['message_id' => 2,
             'points' => 2],
        ['message_id' => 3,
             'points' => 2]];

// max value
$max = max(array_column($arr, 'points'));

Getting the associative key is where it gets a little more tricky, considering that you might actually want multiple keys (if $max matches more than one value). You can do this with an anonymous function inside array_map, and use array_filter to remove the null values:

// keys of max value
$keys = array_filter(array_map(function ($arr) use ($max) {
    return $arr['points'] == $max ? $arr['message_id'] : null;
}, $arr));

Output:

array(1) {
  [0]=>
  int(1)
}

If you do end up with multiples keys but are only interested in the first match found, then simply reference $keys[0].

Answer:

another simple method will be

$max  = array_map( function( $arr ) {
  global $last;
  return (int)( ( $arr["Total"] > $last ) ? $arr["Total"] : $last );
}, $array );

print_r( max( $max ) );

Answer:

<?php
$myarray = array(
    0 => array(
        'Key1' => 'Key1',
        'Total' => 13,
    ),
    1 => array(
        'Key2' => 'Key2',
        'Total' => 117,
    ),
    2 => array(
        'Key2' => 'Key3',
        'Total' => 39,
    ),
);

$out = array();
foreach ($myarray as $item) {
    $out[] = $item['Total'];
}

echo max($out); //117

unset($out, $item);

Answer:

Can be done using array_walk(array_walk_recursive if needed)

$arr is the array you want to search in

$largestElement = null;

array_walk($arr, function(&$item, $key) use (&$largestElement) {
    if (!is_array($largestElement) || $largestElement["Total"] < $item["Total"]) {
        $largestElement = $item;
    }
});

Answer:

You can use php usort function:
http://php.net/manual/en/function.usort.php

A pretty illustrative example is given here:

<?php
function cmp($a, $b)
{
 return strcmp($a["fruit"], $b["fruit"]);
}

$fruits[0]["fruit"] = "lemons";
$fruits[1]["fruit"] = "apples";
$fruits[2]["fruit"] = "grapes";

usort($fruits, "cmp");

while (list($key, $value) = each($fruits)) {
 echo "$fruits[$key]: " . $value["fruit"] . "\n";
}
?>

So it will sort the max value to the last array index.

Output:

$fruits[0]: apples
$fruits[1]: grapes
$fruits[2]: lemons

This example is given on aforementioned link

Answer:

array_reduce accepts a 3rd “initial” parameter. Use this to avoid the bad practice of using “@” error suppression :

$data = array_reduce($data, function ($a, $b) {
    return $a['Total'] > $b['Total'] ? $a : $b ;
},['Total' => 0]);

print_r($data);

PHP 7.4

$data = array_reduce($data, fn(a,b) => $a['Total'] > $b['Total'] ? $a : $b, ['Total' => 0]);