Algorithm
Input: [1, 1, 3, 1, 1, 5, 7, 5, 8]
Output: [
[3] => 1,
[7] => 1,
[8] => 1,
[5] => 2,
[1] => 4,
]
- Initialize the
occurances
as empty array = [] - Loop through the input array
- If already set
$occurances[$value]
,- Then
$occurances[$value] = $occurances[$value] + 1;
- Else
$occurances[$value] = 0;
- Then
- Sort this
$occurances
array - Return the
$occurances
array;
Code Examples
#1 Code Example with PHP Programming
Code -
PHP Programming
<?php
$inputs = [1, 1, 3, 1, 1, 5, 7, 5, 8];
$occurances = [];
foreach ($inputs as $value) {
$occurances[$value] = ($occurances[$value] ?? 0) + 1;
}
// Sort
asort($occurances);
echo "Output Array:";
print_r($occurances);
Copy The Code &
Try With Live Editor
Input
[1, 1, 3, 1, 1, 5, 7, 5, 8]
Output
[
[3] => 1,
[7] => 1,
[8] => 1,
[5] => 2,
[1] => 4,
]
Demonstration
Write a PHP Code to find the numbers with less occurance start to finish with number of occurance