w3resource

PHP Array Exercises : Get the largest key in an array


16. Get the Largest Key in an Array

Write a PHP script to get the largest key in an array.

Sample Solution:

PHP Code:

<?php
// Define an associative array $ceu with countries as keys and their capitals as values
$ceu = array(
    "Italy" => "Rome",
    "Luxembourg" => "Luxembourg",
    "Belgium" => "Brussels",
    "Denmark" => "Copenhagen",
    "Finland" => "Helsinki",
    "France" => "Paris",
    "Slovakia" => "Bratislava",
    "Slovenia" => "Ljubljana",
    "Germany" => "Berlin",
    "Greece" => "Athens",
    "Ireland" => "Dublin",
    "Netherlands" => "Amsterdam",
    "Portugal" => "Lisbon",
    "Spain" => "Madrid",
    "Sweden" => "Stockholm",
    "United Kingdom" => "London",
    "Cyprus" => "Nicosia",
    "Lithuania" => "Vilnius",
    "Czech Republic" => "Prague",
    "Estonia" => "Tallin",
    "Hungary" => "Budapest",
    "Latvia" => "Riga",
    "Malta" => "Valetta",
    "Austria" => "Vienna",
    "Poland" => "Warsaw"
);

// Use 'max' and 'array_keys' functions to find the maximum key in the associative array
$max_key = max(array_keys($ceu));

// Echo the maximum key
echo $max_key . "\n";

?>

Output:

United Kingdom    

Flowchart:

Flowchart: Get the largest key in an array

For more Practice: Solve these Related Problems:

  • Write a PHP script to iterate through an associative array and determine the largest key using custom comparison logic.
  • Write a PHP function that accepts an associative array and returns the maximum key by sorting the keys numerically or lexicographically.
  • Write a PHP program to extract the keys of an associative array and use max() to find the largest one, then display it.
  • Write a PHP script to implement a manual loop comparing keys of an array to determine the highest one without built-in functions.

Go to:


PREV : Generate Unique Random Numbers within a Range.
NEXT : Lowest Non-zero Integer Function.

PHP Code Editor:



Contribute your code and comments through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.