• 12
name

A PHP Error was encountered

Severity: Notice

Message: Undefined index: userid

Filename: views/question.php

Line Number: 191

Backtrace:

File: /home/prodcxja/public_html/questions/application/views/question.php
Line: 191
Function: _error_handler

File: /home/prodcxja/public_html/questions/application/controllers/Questions.php
Line: 433
Function: view

File: /home/prodcxja/public_html/questions/index.php
Line: 315
Function: require_once

name Punditsdkoslkdosdkoskdo

Find highest value in multidimensional array [duplicate]

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

  • 27
Reply Report
    • Although using @ instead of checking if a value really exists is bad practice, this is by far most correct answer. array_reduce is meant for these kind of solutions.

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

  • 11
Reply Report
      • 2
    • You can init it with "$max= ~PHP_INT_MAX;" Check the basics of finding the min number. The other option is to init it with first member of array
      • 2
    • because you need to have minimal value to compare with first time and you need to be sure that this value is smaller than first element. It could be done also with assiging the first element of array but then I would need to start loop from second element in array.
    • You could always just initialize it as $max = null; then simply add one more condition to check that $max has already been set, like if($v['Total']>$max || !$max). In that case, the first time it runs through the loop and there isn't a $max value defined, it will set one. The assumption is that, even if it's the one and only value, it would technically be the max regardless of whatever arbitrary minimum you've hard coded.

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].

  • 7
Reply Report
<?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);
  • 2
Reply Report

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;
    }
});
  • 1
Reply Report

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

  • 1
Reply Report
      • 2
    • @MarcelloMönkemeyer what exactly is the additional overhead which you are referring here? To get a single value(max or min) whole array needs to be traversed (by comparing). The function above also does the same thing, unless i am missing something here!
      • 2
    • The actual sorting, because it requires multiple traversals and comparisons as well as repeatedly moving and repositioning array keys. Depending on the implemented sorting algorithm (unfortunately, I don't know which one PHP uses), this can grow exponential. It may not be of any visible difference for small arrays and when used few times, but imagine it being constantly used in a framework like Symfony or Laravel - that'd be a huge bummer.
      • 1
    • I wouldn't recommend using a complex sort algorithm for something like getting a single value out of an array. Actually, sorting should only be done when really needed. The additional overhead isn't worth a "cool-looking" solution.

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]);
  • 0
Reply Report

Warm tip !!!

This article is reproduced from Stack Exchange / Stack Overflow, please click

Trending Tags

Related Questions