Andy
Andy

Reputation: 45

Using array_count_values in foreach loop

I would like the sample output as below.

1: 2 occurrences

2: 3 occurrences

3: 2 occurrences

4: 1 occurrence

5: 1 occurrence

7: 1 occurrence

the number of occurrences is based on the user input in a form format. Below is the Html code that I use for the user to type in the number.

<!DOCTYPE html>
<html>
<style>
h1{
text-align:center;
}
form{
text-align:center;
margin:auto;
border-style: solid;
width:700px;
height:250px;
}
</style>
<body>

<form action="page2" method="get">
<h1>Algorithm Calculator</h1>
<label for="fname">Enter Number with Comma <br> eg: 
1,2,3,4,4,5,5,7</label><br><br>
<input type="text" id="number" name="number"><br> 
<br>
<input type="submit" value="Confirm">
</form> 
</body>
</html>

Second-page code

<?php
$number=$_GET['number'];
$result = array();
$result = explode(',',$number);
foreach ($result as $value){
echo "$value = ".array_count_values($result) 
[$value]." occurrences <br>";
}
?>

I only want my code to loop once but it loop more than once if the user input the same number twice. Below is my output.

1 = 1 occurrences

2 = 1 occurrences

3 = 1 occurrences

4 = 2 occurrences

4 = 2 occurrences (i do not want this to loop twice)

Upvotes: 0

Views: 141

Answers (3)

RiggsFolly
RiggsFolly

Reputation: 94642

Loop over the result of the a array_count_values() and its easy.

$number='9,9,4,4,22,22,22';
$result = explode(',',$number);
print_r(array_count_values($result));

foreach(array_count_values($result) as $n=>$occ) {
    echo "$n = $occ occurrences <br />" . PHP_EOL;
}

RESULT

The array_count_value() produces an array with the key being the numbers being counted and the value as the occurances of the numbers

Array
(
    [9] => 2
    [4] => 2
    [22] => 3
)

So the output is

9 = 2 occurrences <br />
4 = 2 occurrences <br />
22 = 3 occurrences <br />

Upvotes: 0

Kishen Nagaraju
Kishen Nagaraju

Reputation: 2180

array_count_values function provides the unique elements in an array as the keys and also provides the number of occurrences as the values in the array. So the solution can be as mentioned below:

<?php
    $number=$_GET['number'];
    $result = array();
    $result = explode(',',$number);
    foreach (array_count_values($result) as $key => $value) {
        echo "{$key} = {$value} occurrences <br />";
    }
?>

Upvotes: 1

pr1nc3
pr1nc3

Reputation: 8338

You will need to handle the user input then before going inside your loop.

$result = explode(',',$number);
foreach (array_unique($result) as $value){
   echo "$value = ".array_count_values($result) 
   [$value]." occurrences <br>";
}

You will keep only the unique values in your array so you will loop only once per value.

Upvotes: 1

Related Questions