Skip to content

Instantly share code, notes, and snippets.

@kodie
Created August 29, 2020 00:37
Show Gist options
  • Save kodie/bfe1d86ede013e0f19855c7dddcb1b33 to your computer and use it in GitHub Desktop.
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
<?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