Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find the maximum and minimum date by key

Tags:

arrays

php

I have an array

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

How do I find maximum and minimum by key( date)?

For example:

max => 2011-01-01
min => 2008-05-01
like image 966
kn3l Avatar asked Dec 03 '22 02:12

kn3l


1 Answers

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

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

Or for the maximum:

$max_key = array_search(max($a), $a);
like image 82
mario Avatar answered Dec 15 '22 23:12

mario