To find the maximum value of an array in php, we can use the php max() function.

$max = max($values)

The max function returns the “highest” 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 maximum of an array in php, we use the php max() function.

Let’s say we have the following array of integers:

$sample_array = array(0,4,1,-5)

We can easily get the maximum of this array by calling the php max() function.

$sample_array = array(0,4,1,-5);

echo max($sample_array); // -5

php max() for Arguments of Different Types

The php max() 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 max() function to compare an array with multiple types, you need to understand how the max() function works with these different types.

For strings, the max() function assigns a value of 0.

So if I call the php max() function with the following arguments, the returned value will be “example string”, because 1 is greater than 0.

echo max("example string",1);  // 1 

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 max() method with arrays:

echo json_encode(max(array(0,3,4),array(0,5,1)));  // [0,5,1] because 5 > 3 
echo json_encode(max(array(0,3,4),array(-10,0,5,1)));  // [-10,0,5,1] because the array is longer than [0,3,4]
echo json_encode(max(array(0,3,4),"example_string"));  // [0,3,4] 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 max() to Find the Maximum Value Between Dates

The max() function can also find the maximum value 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 max($dt1,$dt2)->format(DateTime::RFC3339) // 2021-12-07T18:34:00+00:00

Hopefully this post has been beneficial for you to understand how you can calculate the maximum of an array in php with the php max() function.

Categorized in:

PHP,

Last Update: March 21, 2024