PHP min() function


The min() function in PHP returns the smallest value from a set of provided values. Similar to max(), it can be used with a variable number of arguments and can handle both arrays and individual values.

Syntax:

min(mixed $value1, mixed $value2, mixed ...$values): mixed
  • $value1: The first value to compare.
  • $value2: The second value to compare.
  • $values: (optional) Additional values to compare. You can pass multiple arguments.
  • Return Value: Returns the lowest value among the provided arguments. If the input is an array, it returns the smallest value in the array.

Example 1: Finding the Minimum of Two Numbers

<?php echo min(5, 10); ?>

Output:

5

Explanation: Among the values 5 and 10, the smallest is 5.

Example 2: Finding the Minimum of Multiple Numbers

<?php echo min(3, 7, 2, 5); ?>

Output:

2

Explanation: Among the values 3, 7, 2, and 5, the smallest is 2.

Example 3: Using an Array

<?php $numbers = [1, 3, 5, 7, 2]; echo min($numbers); ?>

Output:

1

Explanation: The min() function finds the smallest value in the array [1, 3, 5, 7, 2], which is 1.

Example 4: Finding the Minimum of Mixed Types

<?php echo min(3.5, 2, 5.5, -1); ?>

Output:

-1

Explanation: Among the values 3.5, 2, 5.5, and -1, the smallest is -1.

Example 5: Working with Strings

<?php echo min("apple", "banana", "grape"); ?>

Output:

apple

Explanation: The min() function compares strings based on their ASCII values. In this case, "apple" comes before "banana" and "grape".

Key Points:

  • The min() function can accept both individual values and arrays.
  • It can handle various data types, including integers, floats, and strings.
  • If multiple data types are provided, it compares them based on their type and value.
  • The function will return the first lowest value if multiple minimum values are present.

In summary, the min() function is a straightforward and effective way to determine the smallest value from a set of inputs in PHP, making it useful for various applications.