100, "2010-05-04" =>400, "2008-05-01" =>800, "2011...">

How to find the maximum and minimum date by key

I have an array

$a = array(
           "2010-05-03" =>100,
          "2010-05-04" =>400,   
           "2008-05-01" =>800,
          "2011-01-01" =>800
     ); 

How to find the maximum and minimum on key( date)?

For instance:

max => 2011-01-01
min => 2008-05-01
+3
source share
5 answers

I would be lazy and just let PHP look twice over the array. To find the minimum and the second time, to find the first matching key for this value:

$min_key = array_search(min($a), $a);

Or for maximum:

$max_key = array_search(max($a), $a);
+8
source

(Not sure if you want the values ​​for the max and min keys or the keys for the max and min values.)

This returns the values ​​for the max / min keys:

$keys = array_keys($a);
$min = $a[min($keys));
$max = $a[max($keys));
+4
source
$maxK = $a[0];
$minK = $a[0];
foreach($a as $k => $v) {
    if($v > $a[$maxK]) $maxK = $v;
    if($v < $a[$minK]) $minK = $v;
}

, . / :

$maxKey = $maxK;
$maxValue = $a[$maxK];
$minKey = $minK;
$minValue = $a[$minK];
+2

array_keys, natcasesort.

, :

<?php
    $testData = array(
        "2010-05-03" =>100,
        "2010-05-04" =>400,   
        "2008-05-01" =>800,
        "2011-01-01" =>800
    );

    natcasesort($testKeys = array_keys($testData));

    echo 'Min: ' . $testKeys[0] . ', max: ' . $testKeys[count($testKeys) - 1] . '<br />';
?>
+2
asort($a);
$keys = array_keys($a);
$min = $keys[0];
$max = $keys[count($keys) - 1];

,

$min = array_search(min($a), $a);
$max = array_search(max($a), $a);
+1

All Articles