How to count array value in PHP
If you want to implement a function similar to PHP’s array_count_values without using any built-in array functions, you can do it manually using a loop. Here’s an example:
<?php
function customArrayCountValues($array) {
$counts = []; // Initialize an empty associative array to store counts.
foreach ($array as $value) {
// Check if the value already exists in the counts array.
if (isset($counts[$value])) {
$counts[$value]++; // Increment the count.
} else {
$counts[$value] = 1; // Initialize the count to 1.
}
}
return $counts;
}
// Example usage
$inputArray = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple'];
$result = customArrayCountValues($inputArray);
// Output the result
print_r($result);
?>
Output:
Array
(
[apple] => 3
[banana] => 2
[orange] => 1
)
Explanation:
- Initialize an Empty Array: Start with an empty array $counts to store the counts.
- Iterate Over Input Array: Loop through each element of the input array.
- Check for Existing Key: If the key (value from the array) already exists in $counts, increment its value.
- Add New Key: If the key does not exist, set its value to 1.
- Return the Counts Array: After the loop, return the $counts array.