How to Find Minimum and Maximum Values in an Array in PHP

Laravel 6 , PHP , Laravel , Laravel 7

Nicesnippets

729

20-12-2019


Hi Guys,

In this blog, I will show how to get minimum and maximum value from an aaray in php. "min()" function returns the lowest value from that array. If at least two parameters are provided, min() returns the smallest of these values.

The max() function returns highest value from that array in php. You will find maximum value in array.

Solution 1 : Minimum Value

/**

* The attributes that are mass assignable.

*

* @var array

*/

public function getMinValue()

{

$myArray = [100,20,30,50,220,3,22,56];

$minValue = min($myArray);

dd($minValue);

}

Solution 2 : Minimum Value using foreach loop

/**

* The attributes that are mass assignable.

*

* @var array

*/

public function getMinValue()

{

$myArray = [1000,500,10,56,560,6,4];

$minValue = $myArray[0];

// get lowest or minimum value in array using foreach loop

foreach($myArray as $key => $val){

if($minValue > $val){

$minValue = $val;

}

}

dd($minValue);

}

Solution 1 : Maximum Value

/**

* The attributes that are mass assignable.

*

* @var array

*/

public function getMaxValue()

{

$myArray = [100,20,30,50,220,3,22,56];

$maxValue = max($myArray);

dd($maxValue);

}

Solution 2 : Maximum Value using foreach loop

/**

* The attributes that are mass assignable.

*

* @var array

*/

public function getMaxValue()

{

$array = [1000,500,10,56,560,6,4];

$maxValue = $array[0];

// get highest or maximum value in array using foreach loop

foreach($array as $key => $val){

if($maxValue < $val){

$maxValue = $val;

}

}

dd($maxValue);

}

It will help you...


Recommended Posts