PHP Get Highest Value from Array

前端 未结 16 1274
耶瑟儿~
耶瑟儿~ 2020-11-28 07:05

I\'m trying to get hold of the largest value in an array, while still preserving the item labels. I know I can do this by running sort(), but if I do so I simply lose the la

相关标签:
16条回答
  • 2020-11-28 07:39
    <?php 
    $array = array("a"=>1,"b"=>2,"c"=>4,"d"=>5); 
    
    foreach ($array as $key => $value) {
       if ($value >= $max) 
        $max = $key;     
    }
    echo " The array in largest number :".$max."<br/>";
    ?> 
    
    0 讨论(0)
  • 2020-11-28 07:40
    $ee = array('a' => 50, 'b' => 25, 'c' => 5, 'd' => 80, 'e' => 40, 'f' => 152, 'g' => 45, 'h' => 28);
    $Acurr = '';
    $Amax = 0;
    
    foreach($ee as $key => $value) {
        $Acurr = $value;    
    
        if($Acurr >= $Amax) {
            $Amax = $Acurr; 
        }
    }
    
    echo "greatest number is $Amax";
    
    0 讨论(0)
  • 2020-11-28 07:42

    If you just want the largest value in the array use the max function. This will return the largest value, although not the corresponding key. It does not change the original array.

    If you care about the the key you could then do

    $key = array_search(max($array), $array)
    

    (Edited to include @binaryLV's suggestion)

    0 讨论(0)
  • 2020-11-28 07:43

    greatestValue=> try this its very easy

    $a=array(10,20,52,105,56,89,96);
    $c=0;
    foreach($a as $b)
    {
    if($b>$c)
    $c=$b;
    
    }
    echo $c;
    
    0 讨论(0)
提交回复
热议问题