Php max value in array column

I know this question is old, but I'm providing the following answer in response to another question that pointed here after being marked as a duplicate. This is another alternative I don't see mentioned in the current answers.

I know there's a function called max but that doesn't work with a multidimensional array like this.

You can get around that with array_column which makes getting the maximum value very easy:

$arr = [['message_id' => 1,
             'points' => 3],
        ['message_id' => 2,
             'points' => 2],
        ['message_id' => 3,
             'points' => 2]];

// max value
$max = max[array_column[$arr, 'points']];

Getting the associative key is where it gets a little more tricky, considering that you might actually want multiple keys [if $max matches more than one value]. You can do this with an anonymous function inside array_map, and use array_filter to remove the null values:

// keys of max value
$keys = array_filter[array_map[function [$arr] use [$max] {
    return $arr['points'] == $max ? $arr['message_id'] : null;
}, $arr]];

Output:

array[1] {
  [0]=>
  int[1]
}

If you do end up with multiples keys but are only interested in the first match found, then simply reference $keys[0].

[PHP 4, PHP 5, PHP 7, PHP 8]

maxFind highest value

Description

Alternative signature [not supported with named arguments]:

max[array $value_array]: mixed

Note:

Values of different types will be compared using the standard comparison rules. For instance, a non-numeric string will be compared to an int as though it were 0, but multiple non-numeric string values will be compared alphanumerically. The actual value returned will be of the original type with no conversion applied.

Caution

Be careful when passing arguments of different types because max[] can produce unpredictable results.

Parameters

value

Any comparable value.

values

Any comparable values.

value_array

An array containing the values.

Return Values

max[] returns the parameter value considered "highest" according to standard comparisons. If multiple values of different types evaluate as equal [e.g. 0 and 'abc'] the first provided to the function will be returned.

If an empty array is passed, then false will be returned and an E_WARNING error will be emitted.

Examples

Example #1 Example uses of max[]

See Also

  • min[] - Find lowest value
  • count[] - Counts all elements in an array or in a Countable object

keith at bifugi dot com

6 years ago

The simplest way to get around the fact that max[] won't give the key is array_search:



This could also be done with array_flip, though overwriting will mean that it gets the last max value rather than the first:



To get all the max value keys:

deoomen

3 months ago

Watch out after PHP 8.0!

Sample code:



Before PHP 8.0 will return int[0] but since PHP 8.0 above code returns string["hello"]!!

volch5 at gmail dot com

8 years ago

max[] [and min[]] on DateTime objects compares them like dates [with timezone info] and returns DateTime object.


It works at least 5.3.3-7+squeeze17

marcini

13 years ago

Note that max[] can compare dates, so if you write something like this:



you will get: 2009-03-15.

costinu

10 years ago

max[null, 0] = null
max[0, null] = 0

Alex Rath

12 years ago

Notice that whenever there is a Number in front of the String, it will be used for Comparison.



But just if it is in front of the String

ries at vantwisk dot nl

13 years ago

I had several occasions that using max is a lot slower then using a if/then/else construct. Be sure to check this in your routines!

Ries

ReVo_

8 years ago

Sometimes you could need to get the max from an array which looks like this:


all max functions i see around don't provide a way to get the max value of the values in [example] key "b"



output: 43

michaelangel0 at mail.com

15 years ago

Matlab users and others may feel lonely without the double argument output from min and max functions.

To have the INDEX of the highest value in an array, as well as the value itself, use the following, or a derivative:

johnphayes at gmail dot com

16 years ago

Regarding boolean parameters in min[] and max[]:

[a] If any of your parameters is boolean, max and min will cast the rest of them to boolean to do the comparison.
[b] true > false
[c] However, max and min will return the actual parameter value that wins the comparison [not the cast].

Here's some test cases to illustrate:

1.  max[true,100]=true
2.  max[true,0]=true
3.  max[100,true]=100
4.  max[false,100]=100
5.  max[100,false]=100
6.  min[true,100]=true
7.  min[true,0]=0
8.  min[100,true]=100
9.  min[false,100]=false
10. min[100,false]=false
11. min[true,false]=false
12. max[true,false]=true

php at rijkvanwel dot nl

11 years ago

To get the largest key in an array:

sun at drupal dot org

11 years ago

Note that max[] throws a warning if the array is empty:



So make sure your data isn't empty.

info at osworx dot net

3 years ago

Be aware if a array like this is used [e.g. values from a shopping cart]:

The result will be: 39,27 and not - as expected - 175,80

So, to find the max value, use integer only like:

and you will get the correct result: 17580

harmor

14 years ago

A way to bound a integer between two values is:



which is the same as:



So if you wanted to bound an integer between 1 and 12 for example:

Input:


Output:
1
1
6
12
12

levim at php dot net

10 years ago



- This function is not actually recursive, but fulfills the requirement that it works on sub-arrays.  I do this because PHP is not very good at recursion.  I also did it because I enjoy doing things this way. 
- It returns something of type int, never a string representation of an int. The exception is when you provide an array that does not contain any integers.  It will then return NULL.
- It ignores non-array, non-int values.

blackmac01 at gmail dot com

2 years ago

In response to: keith at bifugi dot com

If you want to find the specific key[s] that match the maximum value in an array where the values may be duplicated, you can loop through and perform a simple check:


This produces consistent results and will scale well in terms of performance, whereas functions like array_search and array_flip can lead to degraded performance when dealing with large amounts of data.

toon dot baeyens at gmail dot com

10 years ago

A little function for multi-dimensional arrays:

Michael Blinn

3 years ago

Be careful using max[] with objects, as it returns a reference not a new object.

chris at candm dt org dt uk

1 year ago

A function to return the key of the max value of an array. For multiple max values, it will return the key of first. Change > to >= to get the last.

function array_max_key[$arr] {
    $maxkey='';
    $maxval=false;
    array_walk[$arr,
        function [&$cval,&$ckey] use[&$maxkey,&$maxval] {
            if [$maxval === false || $cval > $maxval] {
                $maxval = $cval;
                $maxkey = $ckey;
            }
        }
    ];
    return $maxkey;
}

How to get max value in PHP array?

The max[] function of PHP is used to find the numerically maximum value in an array or the numerically maximum value of several specified values. The max[] function can take an array or several numbers as an argument and return the numerically maximum value among the passed parameters.

How do you find the max value in an array?

To get the index of the max value in an array:.
Get the max value in the array, using the Math. max[] method..
Call the indexOf[] method on the array, passing it the max value..
The indexOf method returns the index of the first occurrence of the value in the array or -1 if the value is not found..

Which PHP functions are used to find the lowest and highest values from a list of arguments?

Approach 2 [Using Library Functions] : We use library functions to find minimum and maximum..
Max[]:max[] returns the parameter value considered “highest” according to standard comparisons. ... .
Min[]:min[] returns the parameter value considered “lowest” according to standard comparisons..

How do you find the smallest number in a 2D array Java?

sort[] :.
Declare a 2D int array to sort called data ..
Declare two int s, one to hold the maximum value, the other the minimum value. The initial value of the maximum should be Integer. MIN_VALUE and the initial value of the minimum should be Integer. ... .
Loop through data from 0 to data. length : ... .
Output your result..

Chủ Đề