Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get min and max value in PHP Array

I have an array like this:

  array (0 =>    array (     'id' => '20110209172713',     'Date' => '2011-02-09',     'Weight' => '200',   ),   1 =>    array (     'id' => '20110209172747',     'Date' => '2011-02-09',     'Weight' => '180',   ),   2 =>    array (     'id' => '20110209172827',     'Date' => '2011-02-09',     'Weight' => '175',   ),   3 =>    array (     'id' => '20110211204433',     'Date' => '2011-02-11',     'Weight' => '195',   ), )  

I need to extract minimal and maximal Weight values. In this example

$min_value = 175

$max_value = 200

Any help on how to do this ? Thank you !

like image 970
Peter Avatar asked May 01 '11 03:05

Peter


People also ask

How do I find the smallest number in an array in PHP?

The min() function returns the lowest value in an array, or the lowest value of several specified values.

What is Array_map function in PHP?

The array_map() is an inbuilt function in PHP and it helps to modify all elements one or more arrays according to some user-defined condition in an easy manner. It basically, sends each of the elements of an array to a user-defined function and returns an array with new values as modified by that function.


1 Answers

Option 1. First you map the array to get those numbers (and not the full details):

$numbers = array_column($array, 'weight') 

Then you get the min and max:

$min = min($numbers); $max = max($numbers); 

Option 2. (Only if you don't have PHP 5.5 or better) The same as option 1, but to pluck the values, use array_map:

$numbers = array_map(function($details) {   return $details['Weight']; }, $array); 

Option 3.

Option 4. If you only need a min OR max, array_reduce() might be faster:

$min = array_reduce($array, function($min, $details) {   return min($min, $details['weight']); }, PHP_INT_MAX); 

This does more min()s, but they're very fast. The PHP_INT_MAX is to start with a high, and get lower and lower. You could do the same for $max, but you'd start at 0, or -PHP_INT_MAX.

like image 53
Rudie Avatar answered Sep 22 '22 03:09

Rudie