Created
August 29, 2020 00:37
-
-
Save kodie/bfe1d86ede013e0f19855c7dddcb1b33 to your computer and use it in GitHub Desktop.
Get the key of the array with the lowest or highest value inside of a multidimensional array
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$arr = array( | |
array( | |
'id' => 123, | |
'amount' => 39 | |
), | |
array( | |
'id' => 789, | |
'amount' => 27 | |
), | |
array( | |
'id' => 364, | |
'amount' => 15 | |
), | |
array( | |
'id' => 696, | |
'amount' => 22 | |
) | |
); | |
$amounts = array_column($arr, 'amount'); | |
$lowest_count_key = array_search(min($amounts), $amounts, true); | |
// => 2 | |
$lowest_count = $arr[$lowest_count_key]; | |
// => array('id' => 364, 'amount' => 15); | |
$highest_count_key = array_search(max($amounts), $amounts, true); | |
// => 0 | |
$highest_count = $arr[$highest_count_key]; | |
// => array('id' => 123, 'amount' => 39); | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment