0

I want to get 'name' of highest value in 'amount' in the array. The code is given below:

$data = [
    ['id' => 0, 'name' => 'Test', 'amount' => 3,],
    ['id' => 1, 'name' => 'Test', 'amount' => 2,],
    ['id' => 2, 'name' => 'Test', 'amount' => 1,],
    ['id' => 3, 'name' => 'Test', 'amount' => 0,],
    ['id' => 4, 'name' => 'High', 'amount' => 6,],
    ['id' => 5, 'name' => 'Test', 'amount' => 4,],
    ['id' => 6, 'name' => 'Test', 'amount' => 5,],
];

3 Answers3

3

You can iterate and compare which is larger and keep the largest.

$max = PHP_INT_MIN;
$largest = [];
foreach($data as $item) {
    if($item['amount'] > $max) {
        $max = $item['amount'];
        $largest = $item;
    }
}

echo $largest['name'];

prints

High

Of course you can use name directly, but I think you want to keep track of the array with the highest amount.

Markus Zeller
  • 8,516
  • 2
  • 29
  • 35
0
usort($data, fn(array $a, array $b): int => $b['amount'] <=> $a['amount']);
$highestAmountItem = reset($data);
$highestName = $highestAmountItem['name'];

We're sorting $data array items by their amounts (using spaceship operator <=>). Then the highest element is the first one, and we can retrieve it via reset function.

yaroslavche
  • 383
  • 1
  • 9
-1

The solution to sort the entire array in descending order of 'amount' offers more flexibility.

array_multisort( array_column($data,'amount'),SORT_DESC,$data);

After that, with the index 0, I have access to the entire line with the highest 'amount'.

var_dump($data[0]);
//array(3) { ["id"]=> int(4) ["name"]=> string(4) "High" ["amount"]=> int(6) }

var_dump($data[0]['name']);
//string(4) "High"
jspit
  • 7,276
  • 1
  • 9
  • 17