Skip to content

PHP Tutorial Numbers and Math

Min and Max

Lesson 74 of 369 2 min read By Deepak Paswan Updated Oct 5, 2026

min() finds the smallest value and max() finds the largest.

index.php
PHP
<?php
echo min(4, 9, 2) . "\n";
echo max(4, 9, 2);
Output
OUTPUT
2
9

With an array

Pass an array to compare all its items.

index.php
PHP
<?php
$scores = [72, 95, 88, 61];

echo "Lowest: " . min($scores) . "\n";
echo "Highest: " . max($scores);
Output
OUTPUT
Lowest: 61
Highest: 95

Empty arrays throw an error

max([]) and min([]) throw a ValueError. Check first.

index.php
PHP
<?php
$scores = [];

if ($scores !== []) {
    echo max($scores);
} else {
    echo "No scores yet";
}
Output
OUTPUT
No scores yet

Keep a value inside a range (clamping)

Combine min() and max() to force a value into limits. For example, a quantity between 1 and 10.

index.php
PHP
<?php
function clamp(int $value, int $low, int $high): int
{
    return max($low, min($high, $value));
}

echo clamp(15, 1, 10) . "\n";
echo clamp(-3, 1, 10) . "\n";
echo clamp(5, 1, 10);
Output
OUTPUT
10
1
5

Sum, product and average

index.php
PHP
<?php
$prices = [120, 80, 100];

echo array_sum($prices) . "\n";
echo array_product([2, 3, 4]) . "\n";
echo array_sum($prices) / count($prices);
Output
OUTPUT
300
24
100

Strings and mixed values

max() can compare strings too, but mixing types gives rules that are hard to remember. Compare values of the same type.

Find the item that has the highest value

index.php
PHP
<?php
$products = [
    ["name" => "Pen", "price" => 12],
    ["name" => "Bag", "price" => 799],
    ["name" => "Book", "price" => 250],
];

$prices = array_column($products, "price");
$mostExpensive = max($prices);

echo "Highest price: $mostExpensive";
Output
OUTPUT
Highest price: 799
lightbulb
Empty array = error
Whenever the list can be empty (search results, filtered items), test it before calling min(), max() or dividing by count().