PHP Get Highest Value from Array
Don't sort the array to get the largest value.
Get the max value:
$value = max($array);
Get the corresponding key:
$key = array_search($value, $array);
PHP Get Highest Count Value from Array
I took @alistaircol Idea and not only fixed it (as it's dependent on the order of the array) but I also simplfied the assignment part so we are not creating 2 new arrays
You can try it here
http://sandbox.onlinephpfunctions.com/code/2fe11fb6040dc68db43fb5cbb858ef3e47394dd2
And here is the code
$items = [370,370,546,55,55,55];
$counted = array_count_values($items);
arsort($counted); //sort descending maintain keys
$occurences = reset($counted); //get the first value (rewinds internal pointer )
$most_frequent = key($counted); //get the key, as we are rewound it's the first key
echo $most_frequent . ' appears ' . $occurences . ' time(s)' . PHP_EOL;
This correctly outputs
55 appears 3 time(s)
Just FYI @alistaircol original answer would fail this test case
http://sandbox.onlinephpfunctions.com/code/fe13e7a0bd00ea1219bc69e2bc5a5aebaf478034
Which is changing the input array from:
$items = [370,370,546,55];
To:
$items = [370,370,546,55,55,55];
It would still output:
370 appears 2 time(s)
In this case when the correct answer is 55 appears 3 time(s)
This way the item with the most is the last one, which exposes that it's based on the order ( which was obvious to me because of using the first index [0]
)
Not to call him out on it, but as it was accepted as the answer I felt I should point that out. Overall though I was a sound approach to the question. So Kudos on that.
UPDATE
One way to get all values that show more then one time is like this:
$items = [370,370,546,55,55,55];
$unique = array_unique( $items );
$diff = array_diff_assoc( $items, $unique);
print_r( $diff );
Which outputs
Array
(
[1] => 370
[4] => 55
[5] => 55
)
You can test it here http://sandbox.onlinephpfunctions.com/code/53df6a8ea7a68768572cfef494e3b715aa13e83b
One note, is that you will get exactly one less occurrence then is actually present.
UPDATE1
We can easily combine these and account for the missing one. See this fiddle to test that
http://sandbox.onlinephpfunctions.com/code/1bc1a30a5e091af3a18fec2c8b48050869108549
And the code:
$items = [370,370,546,55,55,55];
$unique = array_unique( $items );
$diff = array_diff_assoc( $items, $unique);
print_r( $diff );
echo "\n\n";
$counted = array_count_values($diff);
arsort($counted); //sort descending maintain keys
$occurences = reset($counted); //get the first value (rewinds internal pointer )
$most_frequent = key($counted); //get the key, as we are rewound it's the first key
echo $most_frequent . ' appears ' . ( $occurences + 1 ) . ' time(s)' . PHP_EOL;
Outputs ( both the previous ones )
Array
(
[1] => 370
[4] => 55
[5] => 55
)
55 appears 3 time(s)
Oh and if you want the ones that are more then one as a list with no duplicates, then just hit it again with array unique $unique = array_unique($diff);
Cheers!
How to find the highest value in a multidimensional array?
You can try using recursive function
<?php
$ar3=array(123, array(12, 665, array(77, 255, 98, 56), 8), 1155, 676);
function highestValue($ar3) {
foreach($ar3 as $key => $value) {
if (is_array($value)) {
$ar3[$key] = highestValue($value);
}
}
return max($ar3);
}
echo highestValue($ar3); //1155
How to return elements of an array with the highest values?
I'd change the keys and values in the array, then sort by key and return the values of the first key:
$ages = array("Peter" => "35", "Ben" => "37", "Joe" => "43", "Rob" => "43");
$new = array();
foreach ($ages as $name => $age) {
$new[$age][] = $name;
}
uksort($new, function($ka, $kb) { return $kb - $ka; }); // or just krsort($new);
$new = array_values($new)[0]; // <- to use this you have to have at least PHP 5.4
// if you have PHP < 5.4 you can simply do it in two steps:
// $new = array_values($new);
// $new = $new[0];
See it in action!
EDIT: even simpler!
$ages = array("Peter" => "35", "Ben" => "37", "Joe" => "43", "Rob" => "43");
$max = max($ages);
$new = array_keys(array_filter($ages, function ($age) use ($max) { return $age == $max; }));
Get the highest key in array less than 'x'
You can use array_filter()
to get the array with keys less than 38, and the use max()
.
PHP 7.4+
$arr = ['10' => 'a', '20' => 'b', '30' => 'c', '40' => 'd', '50' => 'e'];
$threshold = 38;
// Keep elements under condition:
$limit = array_filter($arr, fn($key) => $key < $threshold, ARRAY_FILTER_USE_KEY);
$max = max(array_keys($limit)); // get the max of remain keys.
var_dump($max);
Outputs:
int(30)
Before PHP 7.4
$threshold = 38;
$arr = ['10' => 'a', '20' => 'b', '30' => 'c', '40' => 'd', '50' => 'e'];
$filtered = array_filter($arr, function($key) use ($threshold) { return $key < $threshold; }, ARRAY_FILTER_USE_KEY);
$max = max(array_keys($filtered));
var_dump($max); // int(30)
how to get maximum value from array php
I get solution from below code..
foreach ($delivery as $key => $value) {
if($key==0){
$mysource = $pickup;
}else{
$mysource = $delivery[$key-1];
}
$data[$key] = $this->GetDrivingDistance($mysource,$value);
if(!empty($data[$key])){
$max = '-9999999 km'; //will hold max val
$found_item = null; //will hold item with max val;
foreach($data as $k=>$v)
{
if($v['distance']>$max)
{
$max = $v['distance'];
$found_item = $v;
}
}
}
}
$dist = $max;
Get the maximum value and the key of the corresponding array from an array of arrays in PHP
Check with following code, it will find max value then max array based on value:
$maxval=max(array_column($array,"bid"));
$maxarray=array_keys(array_column($array,"bid"),$maxval);
print_R($array[$maxarray[0]]);
$array = your array,
Return index of highest value in an array
My solution is:
$maxs = array_keys($array, max($array))
Note:
this way you can retrieve every key related to a given max value.
If you are interested only in one key among all simply use $maxs[0]
How to retrieve all maximum values from array?
To find all keys use array_keys
with a second parameter:
$arr = array('a'=>10,'b'=>20,'c'=>5,'d'=>20);
$key = array_keys($arr, max($arr));
By the way it is said on array_search
man page)
Related Topics
Friendship System with Laravel:Many to Many Relationship
Run Composer with a PHP Script in Browser
PHP Case-Insensitive In_Array Function
Regular Expression to Collect Everything After the Last /
Symfony2 and Date_Default_Timezone_Get() - It Is Not Safe to Rely on the System's Timezone Settings
PHP Replacing Special Characters Like à->A, è->E
What Does "Mass Assignment" Mean in Laravel
PHP Function to Build Query String from Array
Laravel Request::All() Should Not Be Called Statically
How to Redirect Stdout to a File in PHP
Post Content-Length Exceeds the Limit
Why Should I Use Templating System in PHP
Email from PHP Has Broken Subject Header Encoding
Correct Way to Set Bearer Token with Curl