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

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

Patricia Arquette
Release: 2024-10-26 18:01:30
Original
961 people have browsed it

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

Finding Minimum and Maximum Values in a Multidimensional PHP Array

You have an array with multiple subarrays containing key-value pairs. Your goal is to extract the minimum and maximum values for a specific key, in this case, 'Weight'.

Option 1: Using Array Functions

To obtain the list of weights without the rest of the details, use array_column:

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

Then, determine the minimum and maximum weights:

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

Option 2: Array Reduction

Instead of converting the array to an array of weights, you can perform the min/max calculation directly using array_reduce:

<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_MIN);</code>
Copy after login

This approach iterates over each subarray to find the overall minimum or maximum weight.

Option 3: Looping Through Subarrays

If you do not have the previously mentioned array functions available, you can manually loop through the subarrays and track the minimum and maximum values:

<code class="php">$min_value = PHP_INT_MAX;
$max_value = PHP_INT_MIN;

foreach ($array as $subarray) {
  $min_value = min($min_value, $subarray['Weight']);
  $max_value = max($max_value, $subarray['Weight']);
}</code>
Copy after login

The above is the detailed content of How to Efficiently Find 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