0

I know the below code

<?php
    $array = array("1", "hello", "1", "world", "hello");    
    print_r(array_count_values($array));
?>

Will output:

Array
(
    [1] => 2
    [hello] => 2
    [world] => 1
)

I would like to retrieve the value which has been repeated the most, or if there are multiple matching instances which have been repeated the most e.g "hello" and "1" randomise them instead of retrieving the first one.

1 Answer 1

0

Live: http://ideone.com/D1Ydbd

$array = array(1, "hello", 1, "world", "hello",'2','2','2','3','3','3');

$s = array_count_values($array);
$mostRepeated = max($s);

$s = array_filter( $s, function($v) use ($mostRepeated) {
  return $v==$mostRepeated;
});

print_r($s);    
echo array_rand($s);  // randomized

Step:

  • find the highest count
  • remove elements with less frequency
  • return an element random with array_rand

Note that I wrote this function to be transparent whenever there are a single or multiple entries with the same value count.

Sign up to request clarification or add additional context in comments.

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.