To find the minimum value of an array in php, we can use the php min() function.
$min = min($values)
The min function returns the “lowest” value according to standard comparisons in php. If there are multiple values which have the same value, then the first one will be returned.
To get the minimum of an array in php, we use the php min() function.
Let’s say we have the following array of integers:
$sample_array = array(0,4,1,-5)
We can easily get the minimum of this array by calling the php min() function.
$sample_array = array(0,4,1,-5);
echo min($sample_array); // -5
php min() for Arguments of Different Types
The php min() function is able to take arguments of different types and allows us to compare between integers, strings, and arrays.
If you want to use the php min() function to compare an array with multiple types, you need to understand how the min() function works with these different types.
For strings, the min() function assigns a value of 0.
So if I call the php min() function with the following arguments, the returned value will be “example string”, because 0 is less than 1.
echo min("example string",1); // "example string"
If we want to compare arrays with other arrays or values, then there are a few things we need to keep in mind.
First, the longer array is always greater than a shorter array. Second, if they arrays are the same length, then we go from left to right and if there is a difference in elements, the array which contains this element is returned as the minimum. Third, if an array is compared against an integer or string, the array is always bigger.
We can see this below in the following examples of using the php min() method with arrays:
echo json_encode(min(array(0,3,4),array(0,5,1))); // [0,3,4] because 3 < 5
echo json_encode(min(array(0,3,4),array(-10,0,5,1))); // [0,3,4] because the array is smaller than [-10,0,5,1]
echo json_encode(min(array(0,3,4),"example_string")); // "example_string" because arrays are always bigger
If you want to compare boolean variables, you can do this, but the results will not necessarily make sense.
Using php min() to Find the Minimum Between Dates
The min() function can also find the minimum between dates. All we need to do is pass our dates to the function.
$dt1 = new DateTime('2021-12-07 18:34', new DateTimeZone('UTC'));
$dt2 = new DateTime('2021-12-03 11:34', new DateTimeZone('UTC'));
echo min($dt1,$dt2)->format(DateTime::RFC3339) // 2021-12-03T11:34:00+00:00
Hopefully this post has been beneficial for you to understand how you can calculate the minimum of an array in php with the php min() function.