How to Find Minimum Value in Array in PHP
In PHP, you can find the minimum value in an array using the
min() function. Simply pass the array as an argument to min(), and it returns the smallest value.Syntax
The min() function takes an array as input and returns the smallest value found in that array.
min(array $values): mixed- Returns the minimum value from the array.
php
min(array $values): mixedExample
This example shows how to find the minimum number in an array of integers using min().
php
<?php $numbers = [5, 3, 9, 1, 7]; $minimum = min($numbers); echo "The minimum value is: " . $minimum; ?>
Output
The minimum value is: 1
Common Pitfalls
One common mistake is passing multiple arguments instead of an array, which also works but can be confusing. Another is using min() on an empty array, which returns NULL and raises a warning. Always check if the array is not empty before calling min().
php
<?php // Wrong: empty array $empty = []; $result = @min($empty); var_dump($result); // NULL // Right: check before calling min if (!empty($empty)) { echo min($empty); } else { echo "Array is empty."; } ?>
Output
NULL
Array is empty.
Quick Reference
Remember these tips when using min():
- Pass a non-empty array to get the minimum value.
- It works with numbers and strings (lexicographically).
- Use
empty()to avoid errors with empty arrays.
Key Takeaways
Use PHP's built-in
min() function to find the smallest value in an array.Always ensure the array is not empty before calling
min() to avoid unexpected results.min() works with both numeric and string arrays.Passing multiple arguments to
min() also works but passing an array is clearer.Check the return value carefully when working with empty arrays.