Home  >  Article  >  Backend Development  >  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
Patricia ArquetteOriginal
2024-10-26 18:01:30883browse

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>

Then, determine the minimum and maximum weights:

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

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>

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>

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!

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