PHP Array Count Values


 

PHP Array Count Values

PHP Array Count Values: This tutorial will let you know how to count the number of values of an array, PHP provides array_count_values() function to count the number of values. Given examples will illustrate this function

PHP Array Count Values: This tutorial will let you know how to count the number of values of an array, PHP provides array_count_values() function to count the number of values. Given examples will illustrate this function

PHP Array Count Values 

Sometimes  we need to count the number of values, i.e. total number of appearance of an element, in an array. PHP provides array_count_values() function to count the number of variables. 

General description of array_count_values() is given below:

General Format array array_count_values(array $array)
Parameters array $array: Input array
Return Value An associative array

PHP Array Count Values Example 1:

<?php
$array=array("New","Delhi","New","World","World","Cup");
echo"
Initially the values of \$array is:
"; var_dump($array); echo"
Counting the number of values are:
"; print_r(array_count_values($array)); ?>

Output:

Initially the values of $array is:
array(6) {
  [0]=>
  string(3) "New"
  [1]=>
  string(5) "Delhi"
  [2]=>
  string(3) "New"
  [3]=>
  string(5) "World"
  [4]=>
  string(5) "World"
  [5]=>
  string(3) "Cup"
}

Counting the number of values are:
Array
(
    [New] => 2
    [Delhi] => 1
    [World] => 2
    [Cup] => 1
)

Example 2 (Associative Array):

<?php
$array=array('cricket'=>11,'football'=>11,'chess'=>2);
echo"
Initially the values of \$array is:
"; var_dump($array); echo"
Counting the number of values are:
"; print_r(array_count_values($array)); ?>

Output:

Initially the values of $array is:
array(3) {
  ["cricket"]=>
  int(11)
  ["football"]=>
  int(11)
  ["chess"]=>
  int(2)
}

Counting the number of values are:
Array
(
    [11] => 2
    [2] => 1
)

 

Ads