min() finds the smallest value and max() finds the largest.
<?php
echo min(4, 9, 2) . "\n";
echo max(4, 9, 2);
2
9
With an array
Pass an array to compare all its items.
<?php
$scores = [72, 95, 88, 61];
echo "Lowest: " . min($scores) . "\n";
echo "Highest: " . max($scores);
Lowest: 61
Highest: 95
Empty arrays throw an error
max([]) and min([]) throw a ValueError. Check first.
<?php
$scores = [];
if ($scores !== []) {
echo max($scores);
} else {
echo "No scores yet";
}
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.
<?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);
10
1
5
Sum, product and average
<?php
$prices = [120, 80, 100];
echo array_sum($prices) . "\n";
echo array_product([2, 3, 4]) . "\n";
echo array_sum($prices) / count($prices);
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
<?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";
Highest price: 799
Empty array = error
min(), max() or dividing by count().