Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Get value of another key of corresponding highest value in PHP

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,],
];

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

$max = -1;
$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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading