In this tutorial we will learn How To Count array values in PHP. PHP count() function and sizeof() function are used to find total number of values in array. But we can also use array_count_values() function along with array_sum() function to find total number of elements in an array.
Table of Contents
Using PHP count() function
PHP count() function is a built-in function which returns the number of values or elements in an array.
<?php
$array=array("HTML","CSS","JavaScript","PHP");
$count = count($array);
echo $count; //Output 4
?>
Using PHP sizeof() function
PHP sizeof() function is a built-in function which also returns the number of values in an array.
<?php
$array=array("Apple","Orange","Banana");
$count = sizeof($array);
echo $count; //Output 3
?>
count() function and sizeof() function work in the same way, both return the total count of elements in an array and both are interchangeable.
Using PHP array_count_values() function and array_sum() function
In this example we have used both PHP array_count_values() function and PHP array_sum() function together.
array_count_values() function returns an array in which values are number of occurrences of each element of array.
We can find sum of all values of this array (returned by array_count_values() function) using array_sum() function to get the exact number of values or elements present in original array.
<?php
$array=array("Red","Black","Orange","Yellow","Gold");
$array2 = array_count_values($array);
$count = array_sum($array2);
echo $count; //Output 5
?>
5 is the number of elements present in this array.