1

Inside a PHP foreach loop, i have a variable called $levels. This variable gives different values for each loop. The values are all numeric. The numbers will also be common across multiple instances of the loop.

So for example, a few loops may return the number 7, and others might return 4 and one might return 3. I want to be able to determine the most common numeric value generated during the loop.

Any suggestions on how this can be achieved?

BenMorel
  • 34,448
  • 50
  • 182
  • 322
John
  • 6,417
  • 9
  • 27
  • 32
  • rid, thats correct the loop returns a number. most of the time these numbers are unique but sometimes they are the same. i want to return the one that is returned most. if they are all returned the same amount of time then return the highest number. – John Sep 21 '13 at 09:44
  • 1
    Please add the code you have as of now, that will make it easier to help you – luttkens Sep 21 '13 at 09:44
  • Providing a small amount of is considered good habit on SO – Vikas Arora Sep 21 '13 at 09:44
  • Just count how many times every was returned. You can add using `+` – zerkms Sep 21 '13 at 09:45

4 Answers4

1

During the loop you can create an array (e.g. $loopArray) and fill it with all the values generated. At the end of the loop you can compute the mode of your array (example taken from this answer).

$values = array_count_values($loopArray); 
$mode = array_search(max($loopArray), $loopArray);
Community
  • 1
  • 1
Albz
  • 1,982
  • 2
  • 21
  • 33
  • The value that repeats the most in a dataset is called [mode](http://en.wikipedia.org/wiki/Mode_(statistics)) and I posted the code to find it! – Albz Sep 21 '13 at 09:51
0

You can do something like this...

$return = array();
foreach($array as $key => $value) {

    ...

    $return[] = $levels;
}

$count = array_count_values($return);
arsort($count);

$keys = array_keys($count);
echo "The most occurring value is $keys[0][1] with $keys[0][0] occurrences."
Ashwini Agarwal
  • 4,828
  • 2
  • 42
  • 59
0

Store the loop values into an array.

$stuff = array('orange','banana', 'apples','orange', 'xxxxxxx');

$result = array_count_values($stuff);
asort($result);
end($result);
$answer = key($result);

echo $answer;

i hope this will you!

premananth
  • 179
  • 5
  • this works just like Ashwini Agarwal's code. only problem with both is that if a returned value only exists once each, then it doesnt seem to return the highest number. i would like the highest number returned if they all are the same. – John Sep 21 '13 at 10:12
0

You can try something like this

$a = array(1,2,3,4,5,5,6,7,8,8,8,8,9,5,5);
$test = array();
foreach ($a as $value) {
    //echo $value."<br>";
    $test[$value][] = $value;
}
echo "--------------------------<br>";
echo count($test[8]);
Shafeeque
  • 2,039
  • 2
  • 13
  • 28