Algorithm


Input: [1, 1, 3, 1, 1, 5, 7, 5, 8]

Output: [
  [3] => 1,
  [7] => 1,
  [8] => 1,
  [5] => 2,
  [1] => 4,
]

 

  1. Initialize the occurances as empty array = []
  2. Loop through the input array
  3. If already set $occurances[$value],
    1. Then $occurances[$value] = $occurances[$value] + 1;
    2. Else $occurances[$value] = 0;
  4. Sort this $occurances array
  5. 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

x
+
cmd
[1, 1, 3, 1, 1, 5, 7, 5, 8]

Output

x
+
cmd
[ [3] => 1, [7] => 1, [8] => 1, [5] => 2, [1] => 4, ]
Advertisements

Demonstration


Write a PHP Code to find the numbers with less occurance start to finish with number of occurance

Previous
Fibonacci Problem Solution using PHP Language
Next
Get dates of a given Day in PHP and MySQL