Find min/max in a two dimensional array

Here’s one way to get the min and max values:

$min = min(array_column($array, 'Price'));
$max = max(array_column($array, 'Price'));

To return the nested array for the min and max:

$prices = array_column($array, 'Price');
$min_array = $array[array_search(min($prices), $prices)];
$max_array = $array[array_search(max($prices), $prices)];

You could do each in one line since that looked like what you were trying to do:

$min_array = $array[array_search(min($prices = array_column($array, 'Price')), $prices)];
$max_array = $array[array_search(max($prices = array_column($array, 'Price')), $prices)];

PHP >= 5.5.0 needed for array_column() or use the PHP Implementation of array_column().

Using array_map() to get just the min and max:

$min = min(array_map(function($a) { return $a['Price']; }, $array));
$max = max(array_map(function($a) { return $a['Price']; }, $array));

There’s probably a good array_filter() or array_reduce() as well.

Leave a Comment