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

Barbara Streisand
Release: 2024-10-27 08:01:30
Original
473 people have browsed it

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 Different Ways to Determine Minimum and Maximum Values in a PH

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]
];
Copy after login

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

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

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

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!

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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!