GoLang array_count_values

is this article helpful? yes | no
GoLang replacement for PHP's array_count_values [Golang Play | edit | history]
func ArrayCountValues(s []interface{}) map[interface{}]uint {
	r := make(map[interface{}]uint)
	for _, v := range s {
		if c, ok := r[v]; ok {
			r[v] = c + 1
		} else {
			r[v] = 1
		}
	}

	return r
}

PHP array_count_values

PHP original manual for array_count_values [ show | php.net ]

array_count_values

(PHP 4, PHP 5, PHP 7)

array_count_valuesCounts all the values of an array

Description

array array_count_values ( array $array )

array_count_values() returns an array using the values of array as keys and their frequency in array as values.

Parameters

array

The array of values to count

Return Values

Returns an associative array of values from array as keys and their count as value.

Errors/Exceptions

Throws E_WARNING for every element which is not string or integer.

Examples

Example #1 array_count_values() example

<?php
$array 
= array(1"hello"1"world""hello");
print_r(array_count_values($array));
?>

The above example will output:

Array
(
    [1] => 2
    [hello] => 2
    [world] => 1
)

See Also

  • count() - Count all elements in an array, or something in an object
  • array_unique() - Removes duplicate values from an array
  • array_values() - Return all the values of an array
  • count_chars() - Return information about characters used in a string