Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Php associative array sort and get key with highest length [duplicate]

Hey i have an associative array which has keys as String and values as Int. So from that associative array i need to get the key which has the highest value and if multiple keys have the same value then i need the key with the highest length.

So whats the most efficient way of doing this?

example

array = (
    'abc'     => 10,
    'def'     => 8,
    'fff'     => 3,
    'abcr'    => 10,
    'adsfefs' => 10
)

So for this i should get output as adsfefs

like image 398
Sidhant Avatar asked Feb 28 '26 13:02

Sidhant


1 Answers

You can use array_keys and pass a second parameter to filter the returned keys to only include the max ones. You can then find the longest key by using array_reduce and a function that checks the lengths of the strings and throws out the shortest one, like so:

$array = array(
    'abc'     => 10,
    'def'     => 8,
    'fff'     => 3,
    'abcr'    => 10,
    'adsfefs' => 10
);

$keys = array_keys($array, max($array));
$longestKey = array_reduce($keys, function ($a, $b) { return strlen($a) > strlen($b) ? $a : $b; });

var_dump($longestKey);

Be aware that if there are two or more strings that are the same length, it will return the last one.

like image 91
Dan Abrey Avatar answered Mar 03 '26 03:03

Dan Abrey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!