PHP Array array_count_values() Function (With Examples)

In this tutorial, we will learn about the PHP array_count_values() function with its usage, syntax, parameters, return value, and examples. By IncludeHelp Last updated : December 31, 2023

PHP array_count_values() Function

The array_count_values() function will count the occurrences of each individual element and returns an array with elements (key-value) and its occurrences.

Syntax

The syntax of the array_count_values() function:

array_count_values($arr)

Parameters

The parameters of the array_count_values() function:

  • $arr: An array.

Return Value

The return type of this method is array, it returns an associative array of values from array as keys and their count as value.

Sample Input/Output

Input: array(10,20,30,30,20,10,50);
Output:
Array
(
    [10] => 2
    [20] => 2
    [30] => 2
    [50] => 1
)

Input: array("New Delhi", "New Delhi", "Mumbai");
Output:
Array
(
    [New Delhi] => 2
    [Mumbai] => 1
)

PHP array_count_values() Function Example

<?php
//array 1 with integer elements 
$arr1 = array(10,20,30,30,20,10,50);
print_r(array_count_values($arr1));

//array 2 with string values
$arr2 = array("New Delhi", "New Delhi", "Mumbai");
print_r(array_count_values($arr2));    
?>

Output

The output of the above example is:

Array
(
    [10] => 2
    [20] => 2
    [30] => 2
    [50] => 1
)
Array
(
    [New Delhi] => 2
    [Mumbai] => 1
)

To understand the above example, you should have the basic knowledge of the following PHP topics:

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.