Count array values in PHP

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.

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.

Demo

How To Remove Empty Array Elements with PHP How To Remove Common Values from two Arrays with PHP How To Find sum of array values with PHP How To Shuffle array Values in PHP How to Remove Duplicate Values from an array with PHP PHP Sort Associative array by Key PHP Sort Associative array by Value Sort array in numerical order with PHP Sort array in alphabetical order with PHP Sort array in descending order PHP Sort array in ascending order in PHP How to merge two or more arrays in PHP Add elements to the end of an array in PHP Add elements to the start of an array in PHP PHP Remove First Element from an Array PHP Remove Last Element from an Array Check if Key Exists in array PHP Check if Value exists in array PHP How to reverse an array in PHP PHP Print array line by line PHP Echo array values using foreach loop Count array values in PHP PHP Count How Many Times Word appears in String How to Reverse a String with PHP Check if Variable is Null in PHP