array_count_values()

ArvindNexus's avatar
Published Aug 8, 2023
Contribute to Docs

The array_count_values() is a function that counts the occurrences of values in an array. It accepts an input array and returns an associative array, where the keys are the unique values found in the array, and the corresponding values are the number of occurrences of each unique value.

Syntax

$result = array_count_values($array)
  • $array is the array whose values are being counted.
  • $result is the resultant array with counts.

Example

The following example demonstrates the usage of array_count_values() function to count the occurrences of values from the input array $inputArray. When applied, it returns an associative array $resultArray containing the unique values as keys and their corresponding counts as values.

<?php
$inputArray = [1, 2, 3, 2, 4, 1, 2, 4, 5, 1];
$resultArray = array_count_values($inputArray);
print_r($resultArray);
?>

The example will result in the following output:

Array
(
[1] => 3
[2] => 3
[3] => 1
[4] => 2
[5] => 1
)

Codebyte Example

The following runnable example declares an input string $inputString, and converts the string into an array of characters using str_split(). Lastly, the array_count_values() function is applied to $characters, which returns an associative array $resultArray.

Code
Output
Loading...

All contributors

Contribute to Docs

Learn PHP on Codecademy