Reputation: 589
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);
Upvotes: 0
Views: 2020
Reputation: 7485
<?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)
}
Upvotes: 1
Reputation: 703
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)
}
Upvotes: 1
Reputation: 147286
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
)
Upvotes: 3