Home  >  Article  >  Backend Development  >  How to Find the Minimum and Maximum Values in a Multidimensional Array Using PHP?

How to Find the Minimum and Maximum Values in a Multidimensional Array Using PHP?

Patricia Arquette
Patricia ArquetteOriginal
2024-10-27 04:58:29382browse

How to Find the Minimum and Maximum Values in a Multidimensional Array Using PHP?

Extracting Minimum and Maximum Values from a Multidimensional Array in PHP

Given an array with nested values, obtaining the minimum and maximum values for a specific key can be challenging. Consider the following example:

<code class="php">$array = array (
  0 =>
  array (
    'id' => '20110209172713',
    'Date' => '2011-02-09',
    'Weight' => '200',
  ),
  1 =>
  array (
    'id' => '20110209172747',
    'Date' => '2011-02-09',
    'Weight' => '180',
  ),
  2 =>
  array (
    'id' => '20110209172827',
    'Date' => '2011-02-09',
    'Weight' => '175',
  ),
  3 =>
  array (
    'id' => '20110211204433',
    'Date' => '2011-02-11',
    'Weight' => '195',
  ),
);</code>

To extract the minimum and maximum weights, several solutions exist:

Option 1:

  • Map the array to extract the 'Weight' values into a new array ($numbers).
  • Use min() and max() to find the minimum and maximum values.
<code class="php">$numbers = array_column($array, 'Weight');
$min_value = min($numbers);
$max_value = max($numbers);</code>

Option 2:

  • For PHP versions below 5.5, use array_map() to extract the 'Weight' values.
<code class="php">$numbers = array_map(function($details) {
  return $details['Weight'];
}, $array);
$min_value = min($numbers);
$max_value = max($numbers);</code>

Option 4:

  • If only the minimum or maximum value is needed, array_reduce() can be more efficient.
<code class="php">$min_value = array_reduce($array, function($min, $details) {
  return min($min, $details['Weight']);
}, PHP_INT_MAX);
$max_value = array_reduce($array, function($max, $details) {
  return max($max, $details['Weight']);
}, -PHP_INT_MAX);</code>

By employing these techniques, you can effectively retrieve the minimum and maximum values from a multidimensional array in PHP, helping you analyze and process data effectively.

The above is the detailed content of How to Find the Minimum and Maximum Values in a Multidimensional Array Using PHP?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn