Open In App

PHP program to find the maximum and the minimum in array

Last Updated : 20 Aug, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

Finding the maximum and minimum in an array involves determining the largest and smallest values within a given set of numbers. This task is crucial for analyzing data, identifying trends, or filtering outliers. Various methods, from simple traversal to optimized algorithms, can achieve this.
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

Simple Traversal (Linear Scan)

The most straightforward approach to finding the maximum and minimum in an array is by iterating through the array once. During this traversal, we maintain two variables: one for the maximum value and one for the minimum value. As we go through each element, we update these variables whenever a larger or smaller element is encountered.

Example:

<?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

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.

Example:

<?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
$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

Using Single Traversal

This method involves initializing two variables to hold the maximum and minimum values, then iterating through the array and updating these variables whenever a new maximum or minimum is found.

Example: In this example, the findMinMax function initializes the minimum and maximum values to the first element of the array. It then traverses the array starting from the second element, updating the minimum and maximum values whenever a smaller or larger element is found, respectively.

<?php
   function findMinMax($arr) {
    // Initialize min and max with the first element of the array
    $min = $arr[0];
    $max = $arr[0];

    // Traverse the array from the second element
    for ($i = 1; $i < count($arr); $i++) {
        if ($arr[$i] < $min) {
            $min = $arr[$i];
        }
        if ($arr[$i] > $max) {
            $max = $arr[$i];
        }
    }

    return ['min' => $min, 'max' => $max];
}

// Example usage
$arr = [2, 3, 1, 6, 7];
$result = findMinMax($arr);
echo "Maximum integer of the given array: " . $result['max'] . "\n";
echo "Minimum integer of the given array: " . $result['min'] . "\n";

// Output:
// Maximum integer of the given array: 7
// Minimum integer of the given array: 1

$arr = [1, 2, 3, 4, 5];
$result = findMinMax($arr);
echo "Maximum integer of the given array: " . $result['max'] . "\n";
echo "Minimum integer of the given array: " . $result['min'] . "\n";


?>

Output
Maximum integer of the given array: 7
Minimum integer of the given array: 1
Maximum integer of the given array: 5
Minimum integer of the given array: 1

Using array_reduce() Function

The array_reduce() function in PHP applies a callback function iteratively to each element in an array, reducing the array to a single value. It’s used here to find the maximum and minimum values by comparing each element with an accumulator (`$carry`).

Example

<?php
$array = array(3, 1, 6, 2, 8);

$maxValue = array_reduce($array, function($carry, $item) {
    return $carry > $item ? $carry : $item;
}, PHP_INT_MIN);

$minValue = array_reduce($array, function($carry, $item) {
    return $carry < $item ? $carry : $item;
}, PHP_INT_MAX);

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

Output
Maximum value: 8
Minimum value: 1

Using foreach with Initial Variables:

This approach involves initializing two variables, one for the maximum and one for the minimum, and then iterating through the array to update these variables as needed.

Example

<?php
function findMinMax($array) {
    if (empty($array)) {
        return ['max' => null, 'min' => null];
    }

    $max = $array[0];
    $min = $array[0];

    foreach ($array as $value) {
        if ($value > $max) {
            $max = $value;
        }
        if ($value < $min) {
            $min = $value;
        }
    }

    return ['max' => $max, 'min' => $min];
}

// Test arrays
$arr1 = [2, 3, 1, 6, 7];
$arr2 = [1, 2, 3, 4, 5];

// Finding min and max
$result1 = findMinMax($arr1);
$result2 = findMinMax($arr2);

echo "Maximum integer of the given array: " . $result1['max'] . "\n";
echo "Minimum integer of the given array: " . $result1['min'] . "\n";

echo "Maximum integer of the given array: " . $result2['max'] . "\n";
echo "Minimum integer of the given array: " . $result2['min'] . "\n";
?>

Output
Maximum integer of the given array: 7
Minimum integer of the given array: 1
Maximum integer of the given array: 5
Minimum integer of the given array: 1

Using Pairwise Comparison Method

In this method, the array is divided into pairs of elements. Each pair is compared to find the local minimum and maximum. These local minimums and maximums are then compared to find the overall minimum and maximum. This method reduces the total number of comparisons compared to a simple linear scan.

Example:

<?php
function getMinMaxPairwise($array) {
    $n = count($array);
    
    if ($n == 0) {
        return ['max' => null, 'min' => null];
    }

    // Initialize min and max
    if ($n % 2 == 0) {
        $min = $array[0] < $array[1] ? $array[0] : $array[1];
        $max = $array[0] > $array[1] ? $array[0] : $array[1];
        $i = 2;
    } else {
        $min = $array[0];
        $max = $array[0];
        $i = 1;
    }

    // Process pairs
    while ($i < $n - 1) {
        if ($array[$i] < $array[$i + 1]) {
            $min = $array[$i] < $min ? $array[$i] : $min;
            $max = $array[$i + 1] > $max ? $array[$i + 1] : $max;
        } else {
            $min = $array[$i + 1] < $min ? $array[$i + 1] : $min;
            $max = $array[$i] > $max ? $array[$i] : $max;
        }
        $i += 2;
    }

    return ['max' => $max, 'min' => $min];
}

// Example usage
$arr1 = [2, 3, 1, 6, 7];
$arr2 = [1, 2, 3, 4, 5];

$result1 = getMinMaxPairwise($arr1);
$result2 = getMinMaxPairwise($arr2);

echo "Maximum integer of the given array: " . $result1['max'] . "\n";
echo "Minimum integer of the given array: " . $result1['min'] . "\n";

echo "Maximum integer of the given array: " . $result2['max'] . "\n";
echo "Minimum integer of the given array: " . $result2['min'] . "\n";
?>

Output
Maximum integer of the given array: 7
Minimum integer of the given array: 1
Maximum integer of the given array: 5
Minimum integer of the given array: 1



Next Article
Article Tags :

Similar Reads

three90RightbarBannerImg