How to find the maximum and the minimum value in an array using PHP

How to find the maximum and the minimum value in an array using PHP

Sometimes we need to find maximum and minimum value in an array. We know array plays important role in any programming language. We store and parse the value in the array to set and get the data from it. Here we will learn how to find the maximum and minimum value in an array.

Sometimes situations arrive when we need to get a minimum or maximum value from the array. We can get the minimum and maximum value from the array using the customize function else we have another option in PHP.

In PHP we have two inbuilt methods min() and max() that provide us a simple way to get minimum and maximum value from the array. Here we will learn about them and know how to find the maximum and minimum value in an array.

In first we will create a function and with the help of for loop, we can check for minimum and maximum value in an array. In the second we have inbuilt PHP max() and min() function to get the minimum and maximum value in an array.

For more detail, you can check the below code snippet.

Approach 1

 We simply traverse through the array, find its maximum and minimum.

<?php 
// Returns maximum in array 
function getMax($array) 
{ 
$n = count($array); 
$max = $array[0]; 
for ($i = 1; $i < $n; $i++) 
	if ($max < $array[$i]) 
		$max = $array[$i]; 
	return $max;	 
} 

// Returns maximum in array 
function getMin($array) 
{ 
$n = count($array); 
$min = $array[0]; 
for ($i = 1; $i < $n; $i++) 
	if ($min > $array[$i]) 
		$min = $array[$i]; 
	return $min;	 
} 

// Driver code 
$array = array(1, 2, 3, 4, 5); 
echo(getMax($array)); 
echo("\n"); 
echo(getMin($array)); 
?> 

Output:

5
1

Approach 2

We use library functions max() and min() to find the the value.

  1. Max(): The max() function returns the highest value in an array or the highest value of several specified values.
  2. Min(): The min() function returns the lowest value in an array or the lowest value of several specified values.

Let’s understand the above methods using an example.

<?php 
$array = array(1, 2, 3, 4, 5); 
echo(max($array)); 
echo("\n"); 
echo(min($array)); 
?> 

Output:

5
1

So you can see how easy it to get maximum and minimum value in PHP.

Conclusion:

With the help of above two example you can easily get the minimum and maximum value from the array. Min() and Max() methods are very easy to use. Hope it helped you, please let us know if you found any problem in using the above code.

You can also check How to check if a variable is an array in PHP?