简体   繁体   中英

php: Keep only max values in an array?

Given a simple array like

$testarr = array("Donna"=>3, "Luke" => 4, "Pete" =>4, "Lola" => 1);

How can I keep only the max values? I am aware I could do a

max($testarr);

and then loop through the array removing values that differ, but maybe sg like array_filter, or a more elegant one liner solution is available.

Here is your one-liner using array_filter :

<?php

$testarr = array("Donna"=>3, "Luke" => 4, "Pete" =>4, "Lola" => 1);
$max = max($testarr);
$only_max = array_filter($testarr, function($item) use($max){ return $item == $max; });
var_dump( $only_max );

Output:

array(2) {
  ["Luke"]=>
  int(4)
  ["Pete"]=>
  int(4)
}

Note that the closure function is referencing $max . As suggested by @devon , referencing the original array would make the code shorter & general, in exchange for calculation efficiency.

$only_max = array_filter($testarr, 
    function($item) use($testarr){ 
        return $item == max($testarr);
    });

This will get you where you need to go:

<?php
function less_than_max($element)
{
    // returns whether the input element is less than max
    return($element < 10);
}


$array1 = array("a"=>1, "b"=>2, "c"=>3, "d"=>4, "e"=>5);
$array2 = array("a" => 6, "b"=>7, "c"=>8, "d"=>9, "e"=>10, "f"=>11, "g"=>12);
$max = 3;

echo "Max:\n";
print_r(array_filter($array1, "less_than_max"));
echo "Max:\n";
print_r(array_filter($array2, "less_than_max"));
?>

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