0

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.

2
  • so you want to set every key in your array to be the one max value? Commented Sep 24, 2015 at 2:39
  • Nope, just remove keys / values that are lower than the max value. Commented Sep 24, 2015 at 2:40

2 Answers 2

3

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);
    });
Sign up to request clarification or add additional context in comments.

1 Comment

Could make it shorter with $only_max = array_filter($testarr, function($item) use($testarr){ return $item == max($testarr); }); but depending on opcache, your way would be more efficient :) but anyways, good use of a anonymous function.
2

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"));
?>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.