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

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

Barbara Streisand
Release: 2024-10-29 06:19:31
Original
790 people have browsed it

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

How to Determine Minimum and Maximum Values in a Multidimensional PHP Array

In PHP, extracting minimal and maximal values from an array is a straightforward task. To illustrate this, consider the following example:

<code class="php">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>
Copy after login

Option 1: Using Array Functions

Utilize the array_column() function to extract the 'Weight' values:

<code class="php">$weights = array_column($array, 'Weight');</code>
Copy after login

Subsequently, determine the minimum and maximum values:

<code class="php">$minValue = min($weights);
$maxValue = max($weights);</code>
Copy after login

Option 2: Using Array and Map Functions (PHP 5.5 or higher)

аналогичный Option 1, но использует array_map() для извлечения значений:

<code class="php">$weights = array_map(function($row) { return $row['Weight']; }, $array);

$minValue = min($weights);
$maxValue = max($weights);</code>
Copy after login

Option 4: Using Array Reduce for Minimum or Maximum Calculations

For efficiency, use array_reduce() if only minimal or maximal value is required:

<code class="php">$minValue = array_reduce($array, function($minimum, $current) {
    return min($minimum, $current['Weight']);
}, PHP_INT_MAX);</code>
Copy after login

The array_reduce() performs fewer min() operations, making it potentially faster. PHP_INT_MAX represents the initial high value to start the reduction.

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

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template