You are here: Home / Topics / PHP Program for finding the frequency of numbers in given array

PHP Program for finding the frequency of numbers in given array

Filed under: PHP on 2022-11-15 10:58:49

This program is useful for finding how many times any number is placed in any array. Suppose we have an array with elements as follows: 

$a = array (54,85,92,54,16,92,48);

Output will be: 

54 occurs 2 times 

85 occurs 1 times 

92 occurs 2 times 

16 occurs 1 times 

48 occurs 1 times . 

<?php
// Initialize array of elements
$a = array (54,85,92,54,16,92,48);
//If array will store frequencies of element
$fr = array_fill(0, count($a), 0);
$check = -1;
for($i = 0; $i < count($a); $i++)
{
$count = 1;
for($j = $i+1; $j < count($a); $j++)
{
if($a[$i] == $a[$j]) // If duplicate element is found increment count
{
$count++;
//To avoid counting same element again
$fr[$j] = $check;
}
}
if($fr[$i] != $check) //If element is not repeated count will be same
$fr[$i] =$count;
}
echo("The Array Elements are: ");
foreach( $a as $b )
{
echo $b."  ";
}
//Displays the frequency of each element in given array
echo (" frequency of given array elements: " );
for( $i = 0; $i < count($fr); $i++)
{
if($fr[$i] != $check)
{
echo( $a[$i] ." occurs " );
echo( $fr[$i]." times.");
echo(" ");
}
}
return 0;
?>

 

I hope you find this helpful.

About Author:
S
Shyam Dubey     View Profile
If you are good in any field. Just share your knowledge with others.