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?

4
  • 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. Commented Sep 21, 2013 at 9:44
  • 1
    Please add the code you have as of now, that will make it easier to help you Commented Sep 21, 2013 at 9:44
  • Providing a small amount of is considered good habit on SO Commented Sep 21, 2013 at 9:44
  • Just count how many times every was returned. You can add using + Commented Sep 21, 2013 at 9:45

4 Answers 4

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

1 Comment

The value that repeats the most in a dataset is called mode and I posted the code to find it!
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!

1 Comment

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.
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."

Comments

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]);

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.