Core\Math::min
Core\Math::min returns the smaller of two values. To find the smallest value in an array, use Core\Arr::min.
It compares numbers, strings, bool values and null. The two values must be of the same type. Strings are compared by their characters, so "apple" is smaller than "pear". 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, so a NaN value is always the result.
When the two values cannot be compared, Core\Math::min 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 discount that must never be larger than the price.
Parameters
$aTOne value: a number, a string, aboolornull.$bTThe other value, of the same type as$a.
Return value
Returns T. The smaller 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 smaller of two numbers, and the smaller of two strings.
// This prints 3, in either order.echo Core\Math::min(3, 7), "\n";echo Core\Math::min(7, 3), "\n";
// This prints 2.25.echo Core\Math::min(2.25, 2.5), "\n";
// -10 is smaller than -1. This prints -10.echo Core\Math::min(-10, -1), "\n";
// Strings are compared by their characters. This prints "apple".echo Core\Math::min('apple', 'pear'), "\n";332.25-10appleNan 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 NAN.echo Core\Math::min(Core\Math::NAN, 0.0), "\n";
// This also prints NAN, even beside the smallest possible `float`.echo Core\Math::min(-Core\Math::INFINITY, 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::min($count, $label), "\n";} catch (RuntimeError $error) { echo "These two values cannot be compared.\n";}NANNANThese two values cannot be compared.Discount never above the price
<?nvs// Shows how a shop keeps a coupon from taking more off an order than the order costs.
class Checkout{ // Returns the price after the coupon, in cents. It is never below zero. public static function toPay(int $priceCents, int $couponCents): int { int $discount = Core\Math::min($couponCents, $priceCents); return $priceCents - $discount; }}
// The coupon is worth 1500 cents. This prints 3490, then 0 for the small order.echo 'Large order, to pay: ', Checkout::toPay(4990, 1500), "\n";echo 'Small order, to pay: ', Checkout::toPay(990, 1500), "\n";Large order, to pay: 3490Small order, to pay: 0