Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return elements of an array with the highest values?

Tags:

php

In my code I have two elements which has the same age "Joe"=>"43" and "Rob"=>"43" .

My code output is:

Joe

I want to output:

Joe and Rob

Because they has the highest value.

This is my code:

<?php
    $cur = 1;

    $age = array("Peter" => "35", "Ben" => "37", "Joe" => "43", "Rob" => "43");
    $new_array = array();
    arsort($age);
    $new_array = $age;
    $key = array_search(max($new_array), $new_array);

    while ($cur > 0) {
        echo $key;
        $cur--;
    }
?>
like image 258
uno Avatar asked Nov 10 '15 07:11

uno


People also ask

How do you return the highest number in an array?

To get the index of the max value in an array: Get the max value in the array, using the Math. max() method. Call the indexOf() method on the array, passing it the max value.

How do you find greater numbers in an array?

To find the largest element, the first two elements of array are checked and the largest of these two elements are placed in arr[0] the first and third elements are checked and largest of these two elements is placed in arr[0] . this process continues until the first and last elements are checked.

How do you find the max 2 elements in an array?

Take two variables and initiliaze them with zero. Iterate through each element of the array and compare each number against these two number. If current number is greater than maxOne then maxOne = number and maxTwo = maxOne. Otherwise if it only greater than maxTwo then we only update maxTwo with current number.

What is the highest element of array index?

range.


1 Answers

I'd change the keys and values in the array, then sort by key and return the values of the first key:

$ages = array("Peter" => "35", "Ben" => "37", "Joe" => "43", "Rob" => "43");
$new = array();

foreach ($ages as $name => $age) {
  $new[$age][] = $name;
}

uksort($new, function($ka, $kb) { return $kb - $ka; }); // or just krsort($new);
$new = array_values($new)[0]; // <- to use this you have to have at least PHP 5.4

// if you have PHP < 5.4 you can simply do it in two steps:
// $new = array_values($new);
// $new = $new[0];

See it in action!

EDIT: even simpler!

$ages = array("Peter" => "35", "Ben" => "37", "Joe" => "43", "Rob" => "43");
$max = max($ages);
$new = array_keys(array_filter($ages, function ($age) use ($max) { return $age == $max; }));
like image 182
Matteo Tassinari Avatar answered Sep 23 '22 16:09

Matteo Tassinari