I have associative array like
array { [company 1]=>array ( [1981] => 1 [1945] => 3 ) [company 2]=>array ( [1990] => 18 [2005] => 13 ) [company 3]=>array ( [1950] => 6 [2012] => 9 ) }
I want to get lowest and highest key i.e. 1945 and 2012. How can i achieve this? I have already searched over stackoverflow and Hightest value of an associative array is the nearest possibility but it gives out min and max value and I want min and max key.
**I don’t want to use foreach loop **
Advertisement
Answer
If you really hate foreach
, here’s a solution:
$arr = array( "Company 1" => array( "1981" => 1, "1945" => 3 ), "Company 2" => array( "1990" => 18, "2005" => 13 ), "Company 3" => array( "1950" => 6, "2012" => 9 ) ); $arr = array_map("array_keys", $arr); $arr = array_reduce($arr, "array_merge", array());
Your $arr
would end up like this:
Array ( [0] => 1981 [1] => 1945 [2] => 1990 [3] => 2005 [4] => 1950 [5] => 2012 )
Now you can use min()
and max()
functions or sort()
it get the highest and lowest value easily.
sort($arr); echo end($arr); /*highest value; actual output: 2012*/ echo reset($arr); /*lowest value; actual output: 1945*/