简体   繁体   中英

Is it possible to get max value more than one in PHP?

I know how to find max value in PHP

 $max = max($var);

but when it has multi max value, it has shown only one value. But how I can get more than one value?

Example : (7,5,8,8,4,7,6)

How can I make both '8' show ?

You can simply use array_filter like as

$arr = [7,5,8,8,4,7,6];
$max = max($arr);
$result = array_filter($arr,function($v)use($max){ return $v == $max;});
print_r($result);

Output

Array
(
    [2] => 8
    [3] => 8
)

Demo

If you don't care about the indexes of the items then this will work:

$biggest = max($var);
$totalOfEach = array_count_values($var);
$totalBiggest = $totalOfEach[$biggest];
$arrayOfBiggest = array_fill(0, $totalBiggest, $biggest);

If you do care about the indexes of the item, then you'll need to filter instead of rebuild the array:

$biggest = max($var);
$filter = function ($value) use ($biggest) { return $biggest === $value; };
$filteredArray = array_filter($var, $filter);

You could opt for the second one as less code though... But it involves iterating each var item which could be costly.

try this:

<?php
$arr=array(7,5,8,8,4,7,6);
$str=getMultipleMax($arr);
echo rtrim($str, ',');
function getMultipleMax($arr){
    $max=$arr[0];
    $maxstr=array();
    foreach($arr as $values){
        if($values > $max){
            $max=$values;
            $maxstr ="";
            $maxstr .=$values.",";
        }else if($values == $max){
            $maxstr .=$values.",";
        }
    }
    return $maxstr;
}

Try with array_count_values , for example:

<?php

$input = [7,5,8,8,4,7,6];
$countValues = array_count_values($input);
$max = max($input);

print('Max: ' . $max) . PHP_EOL;
print('count[max]:' . $countValues[$max]) . PHP_EOL;
print_r($countValues);

Why not sort the list first, then use array_pop to get the next largest value:

$results = array(7,5,8,8,4,7,6);
sort($results);

$first = array_pop($results);
$second = array_pop($results);

This is my appliance code.

Description : Print the multi result when max value more than one

<?php
$test=8; //Var
$results = array(7,5,8,$test,8,4,7,6); //Array
sort($results); //Sort

if(max($results)==$test){ //If Max equal to '8'
echo " You're Engineer ";
$first = array_pop($results);


if(max($results)==$first){//If I have another '8'
    echo " or ";
echo " You're Programmer ";
$second = array_pop($results);

if(max($results)==$second){ //If I have another '8' again
        echo " or ";
echo " Scientist ";}

}

}
?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM