Sign up ×
Stack Overflow is a community of 4.7 million programmers, just like you, helping each other. Join them, it only takes a minute:

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--;
    }
?>
share|improve this question
    
just to clear things up for you and avoid confusion. you have a multidimensional array of associative arrays. An object would be something like a class. – iam-decoder 2 days ago
    
Thank for tha @iam-decoder – LoremIpsum 2 days ago
    
You should not add the interget values as string, but as integer: array("Peter" => 35). Integers are faster than strings, use them where you can :) – Martijn 2 days ago
    
Ok . I will take note of that @Martijn . Thanks :) – LoremIpsum 2 days ago

6 Answers 6

up vote 13 down vote accepted

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; }));
share|improve this answer
    
best, concise, clean answer – iam-decoder 2 days ago
    
@downvoter: care to explain? I'd like to improve my answer if I can! – Matteo Tassinari 2 days ago
    
your answer is fine the way it is. the only concern I can think is that they'd have to be using php 5.4+ to get this script to work with the immediate array access of a returned value on the last line :) – iam-decoder 2 days ago
    
@iam-decoder you're right, I added a note about it! – Matteo Tassinari 2 days ago
    
Why don't you use ksort instead of uksort? – basil 2 days ago

Use:

$people = array("Peter" => "35", "Ben" => "37", "Joe" => "43", "Rob" => "43");
$max = max($people);
$result = array_filter($people, function($age) use ($max){ return $max == $age; });

The result is:

Array
(
    [Joe] => 43
    [Rob] => 43
)
share|improve this answer
    
I see we think alike :) – Matteo Tassinari 2 days ago
    
Yeah, we did it ^_^ – evilive 2 days ago

Just check it manually:

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

$results = array();
foreach ($new_array as $key => $val) {
    if ($val == $max) {
        $results[] = $key;
    }
}

echo implode(' and ', $results);
// will output "joe and bob"
share|improve this answer

I like the answer of @matteo-tassinari and @evilive much more and wanted to propose it myself. But since the question of efficency came up, here is a solution using only one loop and therefore has a linear time complexity:

<?php
$max = ~PHP_INT_MAX;
$result = [];
foreach($age as $key => $value) {
    if($value > $max) {
        $result = [ $key => $value ];
        $max = $value;
    }
    if($value == $max) {
        $result[$key] = $value;
    }
}
var_dump($result);

Edit:

Regarding the discusson about peformance, I wrote a small benchmark script for three kinds of proposed solutions (loop, sort, filter):

<?php

$age = [];

for($i = 0; $i < 400000; $i++) {
    $age['name_'.$i] = rand(0,100);
}

function loop($age) {
    $max = 0;
    $result = [];
    foreach($age as $key => $value) {
        if($value > $max) {
            $result = [ $key => $value ];
            $max = $value;
        }
        if($value == $max) {
            $result[$key] = $value;
        }
    }
    return $result;
}

function filter($ages) {
    $max = max($ages);
    $new = array_filter($ages, function ($age) use ($max) { return $age == $max; });
    return $new;
}

$start = microtime(true);
loop($age);
echo "LOOP:\t" . (microtime(true) - $start.PHP_EOL);
$start = microtime(true);
arsort($age);
echo "SORT:\t" . (microtime(true) - $start.PHP_EOL);
$start = microtime(true);
filter($age);
echo "FILTER:\t" . (microtime(true) - $start.PHP_EOL);

Live Test

Please double-check if this is right, but my timings look something like this:

LOOP:   0.078601121902466
SORT:   0.30844783782959
FILTER: 0.18877291679382
share|improve this answer
    
This is the best answer by my opinion, it runs in linear time complexity. – Tim 2 days ago
    
My solution using max() and array_filter() should still be O(n), so computationally equivalent to this one, isn't it? – Matteo Tassinari 2 days ago
    
@MatteoTassinari Computational complexity is not the same as performance. If an algorithm runs in O(n^2) for 100 items with each step taking 1ms that is 10 seconds. If it runs in O(n) for 100 items with each step taking 1 second that's 100 seconds. Which algorithm is better? – Tim B 2 days ago
    
The order of an algorithm is an important thing to know as it tells you useful things about how it scales with performance, but it's not the only thing or sometimes even the most important thing to know. – Tim B 2 days ago
    
@TimB yes I understand what you mean, but the other user Tim said about "linear time complexity", and in this aspect, both our answers have such property – Matteo Tassinari 2 days ago

I'd do something like this

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

$max = max($age); //get the highest age

foreach ($age as $key => $value) { //iterate through $age array
    if ($value == $max) {          //if the value is equal to max age 
        echo $key."<br />";        // then echo the key
    }
}
share|improve this answer

You can use the array methods next and key.

With next() you will move the array pointer one position. With key() you will get the key of the element of the array pointer. So the final code will be something like this:

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

next($age);
echo key($age);

Check it working here.

share|improve this answer
    
No, this is not the most efficient solution, since sorting has a complexity of O(n*log n): en.wikipedia.org/wiki/Sorting_algorithm – svrnm 2 days ago
    
You are right about the sorting method, thanks :-) – Miguel 2 days ago

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.