Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to find the maximum and minimum in an array

Short answer

max() and min() accept an array:

<?php
 
$numbers = [4, 9, 2, 7];
 
echo max($numbers), "\n";
echo min($numbers);

Output:

9
2

The key of the maximum

To learn which key holds the largest value, pass it to array_search():

<?php
 
$scores = ['Anna' => 82, 'Oleg' => 95, 'Ira' => 78];
 
echo array_search(max($scores), $scores);

Output:

Oleg

Functions used in this recipe

  • max — Returns the largest of the given values.
  • array_search — Searches an array for a value and returns its key.

Thanks for reading!

Donate to the site — we work hard for you.