PHP min() Function Tutorial 🎯

beginner
15 min

PHP min() Function Tutorial 🎯

Welcome to our PHP min() function tutorial! In this lesson, we'll explore one of the most useful functions in PHP - the min() function. This function is a part of the core PHP library and is used to find the minimum value among a group of numbers. Let's dive in!

Understanding the min() function πŸ“

The min() function is a built-in PHP function that accepts an array of numbers as an argument and returns the smallest number in that array.

php
<?php $numbers = [12, 5, 16, 8, 2]; $minimum_number = min($numbers); echo $minimum_number; // Output: 5 ?>

In the example above, we have an array of numbers, and the min() function helps us find the smallest number in that array, which is 5.

Real-world Application πŸ’‘

The min() function is incredibly useful in various real-world scenarios. For instance, when processing user input, you can use the min() function to ensure that the user has entered a valid number within a certain range.

min() with floating-point numbers πŸ“

The min() function also works with floating-point numbers.

php
<?php $numbers = [12.5, 5.1, 16.9, 8.2, 2.0]; $minimum_number = min($numbers); echo $minimum_number; // Output: 2.0 ?>

In this example, the array contains floating-point numbers, and the min() function still returns the smallest number in the array.

min() with empty arrays πŸ“

It's important to note that the min() function returns FALSE when it's called with an empty array.

php
<?php $empty_array = []; $minimum_number = min($empty_array); echo $minimum_number; // Output: FALSE ?>

In this case, the min() function doesn't have any numbers to compare, so it returns FALSE.

Minimum with multiple arrays πŸ“

The min() function can also be used to find the smallest number from multiple arrays. It will return the smallest number found in all the arrays.

php
<?php $array1 = [12, 5, 16, 8, 2]; $array2 = [3, 9, 6]; $minimum_number = min(array_merge($array1, $array2)); echo $minimum_number; // Output: 3 ?>

In this example, we have merged two arrays and used the min() function to find the smallest number among all numbers in both arrays.

Quick Quiz
Question 1 of 1

Which function in PHP helps you find the minimum value among a group of numbers?

Happy coding! πŸš€