Thomas Bengtsson
Thomas Bengtsson

Reputation: 399

Print out the highest value and its key from an array

I'm stuck with an error message that I can't get around: Notice: Array to string conversion. I'm trying to print the highest value and its key of an array.

<?php
$length_array = array();

foreach ($_SERVER as $key => $value) {
    $length = strlen($value);
    $length_array[$key] = $length;
    echo '<pre>'; 
    print_r($key . " = " . $length . " characters"); 
    echo '</pre>';

}

$max_key = array_keys($length_array, max($length_array));
print_r($max_key . " is longest with " . max($length_array) . " characters");
?>

The answer I get is: Array is longest with 444 characters.

How do I get around this?

Upvotes: 0

Views: 99

Answers (1)

miken32
miken32

Reputation: 42696

array_keys() returns an array. If you expect only one key to have this value you can use array_search() instead:

$server  = array_map("strlen", $_SERVER);
$max     = max($server);
$max_key = array_search($max, $server);

echo "$max_key is longest with $max characters";

Upvotes: 1

Related Questions