The basic syntax of the min() function is as follows:
min(mixed $value1, mixed $value2, ...): mixed
Or pass in an array:
min(array $values): mixed
The function returns the smallest value among the passed in parameter.
This is one of the most common uses of min() . You can pass multiple values directly to the function, and it returns the smallest one:
echo min(4, 8, 2, 6); // Output 2
This approach is ideal for quick comparisons of a known number of variables.
When you need to find the minimum value from an array, you can pass it directly into the array:
$numbers = [10, 3, 7, 1, 9];
echo min($numbers); // Output 1
This method is more suitable for scenarios where the data volume is uncertain or data is received from external inputs.
min() can also be used for strings, which compares elements in dictionary order:
echo min("apple", "banana", "cherry"); // Output apple
A string with a letter front will be considered a smaller value.
When the array is an associative array, min() still works properly, it only cares about the values:
$assoc = ["a" => 10, "b" => 5, "c" => 8];
echo min($assoc); // Output 5
Please note that if you are using a multidimensional array, min() will not be processed correctly and the return result may not be as expected.
$prices = [299.99, 149.99, 199.99, 99.99];
$minPrice = min($prices);
echo "The lowest price is:¥{$minPrice}"; // Output The lowest price is:¥99.99
Suppose you get a set of data through the interface:
$json = file_get_contents("https://gitbox.net/api/data");
$data = json_decode($json, true);
$values = array_column($data, 'score');
echo "The minimum score is:" . min($values);
Here we use array_column() to extract the key fields, and then quickly get the minimum value through min() .
min() may return unexpected results when processing boolean or mixed type data, so be sure to clean the data first.
When used for an empty array, min() will return false , be sure to check if the array is empty:
$empty = [];
echo min($empty); // Output false,And may trigger a warning
Such errors can be avoided by judgment:
if (!empty($empty)) {
echo min($empty);
} else {
echo "The array is empty";
}