Skip to main content

PHP find object with highest property value

Posted on January 30, 2020


Given:

$houses = [
  'house1' => [
    'bed' => 2,
    'bath' => 1,
    'garage' => 'no',
  ],
  'house2' => [
    'bed' => 4,
    'bath' => 4,
    'garage' => 'no',
  ],
  'house3' => [
    'bed' => 3,
    'bath' => 2,
    'garage' => 'yes',
  ],
];

Here is a concise way to select the house with the most bathrooms:

$max_bath_house = array_reduce($houses, function($current_max, $house) {
    return ($current_max['bath'] > $house['bath']) ? $current_max : $house;
}, reset($houses));