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:

  1. Initialize an Empty Array: Start with an empty array $counts to store the counts.
  2. Iterate Over Input Array: Loop through each element of the input array.
  3. Check for Existing Key: If the key (value from the array) already exists in $counts, increment its value.
  4. Add New Key: If the key does not exist, set its value to 1.
  5. Return the Counts Array: After the loop, return the $counts array.

Leave a Reply

Your email address will not be published. Required fields are marked *