PHP program to find the maximum and the minimum in array

Given an array of integers, find the maximum and minimum in it.
Examples: 
 

Input : arr[] = {2, 3, 1, 6, 7}
Output : Maximum integer of the given array:7
Minimum integer of the given array:1

Input : arr[] = {1, 2, 3, 4, 5}
Output : Maximum integer of the given array : 5
Minimum integer of the given array : 1


Approach 1 (Simple) : We simply traverse through the array, find its maximum and minimum. 
 

PHP
<?php
// Returns maximum in array
function getMax($array) 
{
   $n = count($array); 
   $max = $array[0];
   for ($i = 1; $i < $n; $i++) 
       if ($max < $array[$i])
           $max = $array[$i];
    return $max;       
}

// Returns maximum in array
function getMin($array) 
{
   $n = count($array); 
   $min = $array[0];
   for ($i = 1; $i < $n; $i++) 
       if ($min > $array[$i])
           $min = $array[$i];
    return $min;       
}

// Driver code
$array = array(1, 2, 3, 4, 5);
echo(getMax($array));
echo("\n");
echo(getMin($array));
?>

Output: 
 

5
1


Approach 2 (Using Library Functions) : We use library functions to find minimum and maximum.

  1. Max():max() returns the parameter value considered “highest” according to standard comparisons. If multiple values of different types evaluate as equal (e.g. 0 and ‘abc’) the first provided to the function will be returned. 
     
  2. Min():min() returns the parameter value considered “lowest” according to standard comparisons. If multiple values of different types evaluate as equal (e.g. 0 and ‘abc’) the first provided to the function will be returned.


 

PHP
<?php
$array = array(1, 2, 3, 4, 5);
echo(max($array));
echo("\n");
echo(min($array));
?>

Output: 
 

5
1

Using sort() and rsort()

To find the maximum and minimum values in an array using sort() and rsort(), first, make copies of the array. Then, sort one in ascending order with `sort()` to find the minimum, and the other in descending order with rsort() to find the maximum.

Example:

PHP
<?php
$array = [2, 5, 1, 8, 3];

// Copy and sort the array in ascending order
$sortedArray = $array;
sort($sortedArray);
$minValue = $sortedArray[0];

// Copy and sort the array in descending order
$reverseSortedArray = $array;
rsort($reverseSortedArray);
$maxValue = $reverseSortedArray[0];

echo "Maximum value: $maxValue\n";
echo "Minimum value: $minValue\n";
?>

Output
Maximum value: 8
Minimum value: 1

Contact Us