0

I want the number of occurrences of each element in array. Note: I can't use inbuilt function like array_count_values()

here's what I have tried.

$a = ['a','b','a','c','a','d'];

$output = [];

for ($i = 0; $i <= count($a);$ i++) {
    $count = 1;
    for($j = $i + 1; $j < count($a); $j++) {
        if ($a[$i] == $a[$j]) {
            $count++;
            $output[$a[$i]] = $count;
        }
    }
}

print_r($output);
Kallol Medhi
  • 457
  • 1
  • 5
  • 17

3 Answers3

3

In PHP7 you can use the NULL coalescing operator to simplify this code:

$a=['a','b','a','c','a','d'];

$output=[];

foreach ($a as $v) {
    $output[$v] = ($output[$v] ?? 0) + 1;
}

print_r($output);

Output:

Array
(
    [a] => 3
    [b] => 1
    [c] => 1
    [d] => 1
)

Demo on 3v4l.org

Nick
  • 138,499
  • 22
  • 57
  • 95
1

As mentioned in the comments array_count_values() is the optimal solution in php. But you must write it out aka show your understanding on how to search an array its rather simple as well.

$a=['a','b','a','c','a','d'];
$output=[]; 

for($i = 0; $i < count($a); $i++){
    if(!isset($output[$a[$i]])){
      $output[$a[$i]] = 1;
    }

    else{
        $output[$a[$i]] = $output[$a[$i]] + 1;
    }
}

var_dump($output);

//output
array(4) {
  ["a"] => int(3)
  ["b"] => int(1)
  ["c"] => int(1)
  ["d"] => int(1)
}
jgetner
  • 691
  • 6
  • 14
  • 3
    OP stipulates no use of inbuilt functions, and yet here we have `isset` and `count` and the OP has for now accepted this answer. – Progrock Jan 21 '20 at 07:07
  • I agree but this isn't about built in functions as both an isset and count can be accomplished with user built functions and loops. I think its more about the op's comfort with standardized things across many languages and versions. – jgetner Jan 21 '20 at 20:39
  • `isset` is quite trickly to replace with a user built function prior to the null coalescing operator. – Progrock Jan 21 '20 at 21:23
  • But yes it's vague as to whether the OP wants to totally omit in-built functions or just the function that would shortcut to the wanted result. – Progrock Jan 21 '20 at 21:30
1
<?php
$items=['a','b','a','c','a','d'];

foreach($items as $item) {
    $result[$item] ??= 0;
    $result[$item]  += 1;
}

var_dump($result);

Output:

array(4) {
  ["a"]=>
  int(3)
  ["b"]=>
  int(1)
  ["c"]=>
  int(1)
  ["d"]=>
  int(1)
}
Progrock
  • 7,373
  • 1
  • 19
  • 25