Home > Article > Backend Development > Here are a few title options, keeping in mind the question format and the article\'s content: Direct and Clear: * How to Find Minimum and Maximum Values in a PHP Array by Key? * What are the Differe
Determining Minimum and Maximum Values in a PHP Array
When working with multidimensional arrays in PHP, extracting the minimum and maximum values for a specific key can be a common task. Suppose you have an array containing objects or arrays with "Weight" as one of the keys, like the example provided:
$array = [ ['Weight' => 200], ['Weight' => 180], ['Weight' => 175], ['Weight' => 195] ];
To obtain the minimum and maximum values of "Weight," you can utilize several approaches:
Option 1: Using array_column() and Array Functions
Extract the weights into a new array using array_column() and then find the min and max values:
$weights = array_column($array, 'Weight'); $min = min($weights); $max = max($weights);
Option 2: Mapping and Array Functions
Similarly, map over the array to extract the weights and then use array functions:
$weights = array_map(function ($item) { return $item['Weight']; }, $array); $min = min($weights); $max = max($weights);
Option 4: Using array_reduce()
If you need only the minimum or maximum value, array_reduce() offers a faster alternative:
$min = array_reduce($array, function ($min, $item) { return min($min, $item['Weight']); }, PHP_INT_MAX);
For the maximum value, start with 0 or -PHP_INT_MAX.
The above is the detailed content of Here are a few title options, keeping in mind the question format and the article\'s content: Direct and Clear: * How to Find Minimum and Maximum Values in a PHP Array by Key? * What are the Differe. For more information, please follow other related articles on the PHP Chinese website!