Core\Math::max
Core\Math::max returns the larger of two values. To find the largest value in an array, use Core\Arr::max.
It compares numbers, strings, bool values and null. The two values must be of the same type. Strings are compared by their characters, so "pear" is larger than "apple". When the two values are equal, the result is the first one. NaN (a value that means "not a number") is smaller than every other float.
When the two values cannot be compared, Core\Math::max throws a RuntimeError. Two arrays, two objects, or a number and a string in two mixed variables are examples.
The examples below show numbers and strings, then NaN and values that cannot be compared, then a stock level that must never go below zero.
Parameters
$aTOne value: a number, a string, aboolornull.$bTThe other value, of the same type as$a.
Return value
Returns T. The larger value. When the two are equal, the result is $a. NaN is smaller than every other float.
Errors
RuntimeErrorWhen the two values cannot be compared: an object, an array, or two values of different kinds.
Examples
Numbers and strings
<?nvs// Shows the larger of two numbers, and the larger of two strings.
// This prints 7, in either order.echo Core\Math::max(3, 7), "\n";echo Core\Math::max(7, 3), "\n";
// This prints 2.5.echo Core\Math::max(2.25, 2.5), "\n";
// -1 is larger than -10. This prints -1.echo Core\Math::max(-10, -1), "\n";
// Strings are compared by their characters. This prints "pear".echo Core\Math::max('apple', 'pear'), "\n";772.5-1pearNan and no order
<?nvs// Shows the result for `NaN`, and what happens when two values cannot be compared.
// `NaN` is smaller than every other `float`. This prints 0.echo Core\Math::max(Core\Math::NAN, 0.0), "\n";
// Two `NaN` values give `NaN`. This prints NAN.echo Core\Math::max(Core\Math::NAN, Core\Math::NAN), "\n";
// A number and a string cannot be compared. This throws a `RuntimeError`.mixed $count = 5;mixed $label = '5';try { echo Core\Math::max($count, $label), "\n";} catch (RuntimeError $error) { echo "These two values cannot be compared.\n";}0NANThese two values cannot be compared.Stock never below zero
<?nvs// Shows how a shop keeps its stock count from going below zero when orders arrive.
class Stock{ // Returns the stock left after an order. It is never below zero. public static function afterOrder(int $inStock, int $ordered): int { return Core\Math::max(0, $inStock - $ordered); }}
int $stock = 12;array<int> $orders = [5, 4, 6];foreach ($orders as int $ordered) { $stock = Stock::afterOrder($stock, $ordered); // This prints 7, then 3, then 0. echo 'Ordered ', $ordered, ', left in stock: ', $stock, "\n";}Ordered 5, left in stock: 7Ordered 4, left in stock: 3Ordered 6, left in stock: 0