Skip to main content

Find the frequency of each element in an array in php

Php program for Find the frequency of each element in an array. Here more information.

<?php
class Occurrence
{
	// Function which is display array elements
	public static function display($arr)
	{
		for ($i = 0; $i < count($arr); ++$i)
		{
			printf("%d  ",$arr[$i]);
		}
		printf("\n");
	}
	// Count occurrence of given array
	public static
	function frequency($arr)
	{
		// Display given array
		Occurrence::display($arr);
		// Create a empty map
		$map = array();
		for ($i = 0; $i < count($arr); $i++)
		{
			if (array_key_exists($arr[$i], $map))
			{
				// When key exists then update value
				$map[$arr[$i]] = $map[$arr[$i]] + 1;
			}
			else
			{
				// Add new element
				$map[$arr[$i]] = 1;
			}
		}
		printf("Occurrence \n");
		//  Display calculated result
		foreach(array_keys($map) as $key)
		{
			printf("%d : %d\n",$key,$map[$key]);
		}
	}
	public static
	function main($args)
	{
		// Array element
		$arr = array(1, 3, 2, 1, 4, 2, 7, 9, 1, 3, 3, 4, 7);
		Occurrence::frequency($arr);
	}
}
Occurrence::main(array());

Output

1  3  2  1  4  2  7  9  1  3  3  4  7
Occurrence
1 : 3
3 : 3
2 : 2
4 : 2
7 : 2
9 : 1




Comment

Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment