[php] 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 !

This question is related to php arrays extract

The answer is


How about without using predefined function like min or max ?

$arr = [4,5,6,7,8,2,9,1];
$val = $arr[0];
$n = count($arr);

for($i=1;$i<$n;$i++) {
if($val<$arr[$i]) {
    $val = $val;        
} else {
    $val = $arr[$i];
}
}
print($val);

?>


$num = 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'));

    foreach($num as $key => $val)   
    {                       
        $weight[] = $val['Weight'];
    }

     echo max($weight);
     echo min($weight);

<?php 
$array = 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',
  ),
);

foreach ($array as $key => $value) {
  $result[$key] = $value['Weight'];
}
$min = min($result);
$max = max($result);

echo " The array in Minnumum number :".$min."<br/>";
echo " The array in Maximum  number :".$max."<br/>";
?> 

print fast five maximum and minimum number from array without use of sorting array in php :-

<?php  

$array = explode(',',"78, 60, 62, 68, 71, 68, 73, 85, 66, 64, 76, 63, 81, 76, 73,  
68, 72, 73, 75, 65, 74, 63, 67, 65, 64, 68, 73, 75, 79, 73");  
$t=0;  
$l=count($array);  
foreach($array as $v)  
{  
 $t += $v;  
}  
 $avg= $t/$l;  
 echo "average Temperature is : ".$avg."  ";   


echo "<br>List of seven highest temperatsures :-"; 
$m[0]= max($array); 
for($i=1; $i <7 ; $i++)
{ 
$m[$i]=max(array_diff($array,$m));
}
foreach ($m as $key => $value) {
    echo "  ".$value; 
}
echo "<br> List of seven lowest temperatures : ";
$mi[0]= min($array); 
for($i=1; $i <7 ; $i++)
{ 
$mi[$i]=min(array_diff($array,$mi));
}

foreach ($mi as $key => $value) {
    echo "  ".$value; 
}
?>  

$Location_Category_array = array(5,50,7,6,1,7,7,30,50,50,50,40,50,9,9,11,2,2,2,2,2,11,21,21,1,12,1,5);

asort($Location_Category_array);
$count=array_count_values($Location_Category_array);//Counts the values in the array, returns associatve array
        print_r($count);
        $maxsize = 0;
        $maxvalue = 0;
        foreach($count as $a=>$y){
            echo "<br/>".$a."=".$y;
            if($y>=$maxvalue){
                $maxvalue = $y;
                if($a>$maxsize){
                    $maxsize = $a;
                }
            }
        }

    echo "<br/>max = ".$maxsize;

foreach ($array as $k => $v) {
  $tArray[$k] = $v['Weight'];
}
$min_value = min($tArray);
$max_value = max($tArray);

It is interesting to note that both the solutions above use extra storage in form of arrays (first one two of them and second one uses one array) and then you find min and max using "extra storage" array. While that may be acceptable in real programming world (who gives a two bit about "extra" storage?) it would have got you a "C" in programming 101.

The problem of finding min and max can easily be solved with just two extra memory slots

$first = intval($input[0]['Weight']);
$min = $first ;
$max = $first ;

foreach($input as $data) {
    $weight = intval($data['Weight']);

    if($weight <= $min ) {
        $min =  $weight ;
    }

    if($weight > $max ) {
        $max =  $weight ;
    }

}

echo " min = $min and max = $max \n " ;

For the people using PHP 5.5+ this can be done a lot easier with array_column. Not need for those ugly array_maps anymore.

How to get a max value:

$highest_weight = max(array_column($details, 'Weight'));

How to get the min value

$lowest_weight = min(array_column($details, 'Weight'));

Examples related to php

I am receiving warning in Facebook Application using PHP SDK Pass PDO prepared statement to variables Parse error: syntax error, unexpected [ Preg_match backtrack error Removing "http://" from a string How do I hide the PHP explode delimiter from submitted form results? Problems with installation of Google App Engine SDK for php in OS X Laravel 4 with Sentry 2 add user to a group on Registration php & mysql query not echoing in html with tags? How do I show a message in the foreach loop?

Examples related to arrays

PHP array value passes to next row Use NSInteger as array index How do I show a message in the foreach loop? Objects are not valid as a React child. If you meant to render a collection of children, use an array instead Iterating over arrays in Python 3 Best way to "push" into C# array Sort Array of object by object field in Angular 6 Checking for duplicate strings in JavaScript array what does numpy ndarray shape do? How to round a numpy array?

Examples related to extract

python pandas extract year from datetime: df['year'] = df['date'].year is not working Accessing last x characters of a string in Bash How to extract one column of a csv file How can I extract the folder path from file path in Python? Extract and delete all .gz in a directory- Linux Read Content from Files which are inside Zip file Get string after character how to extract only the year from the date in sql server 2008? In Excel, how do I extract last four letters of a ten letter string? How can I extract all values from a dictionary in Python?