js

Thursday, January 11, 2024

Explain array_count_values() function in php

The array_count_values() function in PHP is a built-in function that takes an array as input and returns an associative array where the keys are the unique values from the input array, and the values are the counts of each corresponding value in the input array. In other words, it counts the occurrences of each unique value in the array.

Here's the basic syntax of the array_count_values() function:

php
array_count_values(array $array): array
  • Parameters:

    • $array: The input array for which you want to count the occurrences of each unique value.
  • Return Value:

    • An associative array where keys are the unique values from the input array, and values are the counts of each corresponding value.

Here's an example to illustrate how array_count_values() works:

php
$inputArray = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple']; $result = array_count_values($inputArray); print_r($result);

Output:

php
Array ( [apple] => 3 [banana] => 2 [orange] => 1 )

In this example, the input array has three occurrences of 'apple,' two occurrences of 'banana,' and one occurrence of 'orange.' The array_count_values() function returns an associative array with the unique values as keys and their respective counts as values.

This function is handy when you need to analyze the distribution of values in an array and want to know how many times each unique value appears.

No comments:

Post a Comment