Element count with count()
Learn how many elements an array has with the count() function.
The count() function
To find how many elements an array has, use the count() function. You write the array name inside parentheses: count($scores).
For example, for $scores = [85, 92, 78];, count($scores) returns 3. You can print this number with echo or store it in a variable. Knowing the length is often needed to set a loop limit.
sizeof and nested arrays
sizeof() is another name for count(); both return the same result. Modern code prefers count().
To count all elements in nested arrays, pass COUNT_RECURSIVE as the second argument: count($nested, COUNT_RECURSIVE). This also counts elements inside inner arrays. For example, [[1, 2], [3, 4]] gives count 2 and COUNT_RECURSIVE 6.
Exercise Print the element count
Find the element count of $scores = [85, 92, 78]; with count() and print it with echo. Append "\n" at the end. Expected output: 3.
Show example solution
<?php
$scores = [85, 92, 78];
// Print the element count
echo count($scores) . "\n";
Example solution:
<?php
$scores = [85, 92, 78];
// Print the element count
echo count($scores) . "\n";
Test yourself
-
What is the result of count([10, 20, 30])?
echo count([10, 20, 30]);- 2
- 3
- 10
- 30
Show answer
3 — Correct. For a three-element array count returns 3.
-
Complete the count() call
$scores = [85, 92, 78]; echo ____;Show answer
$scores = [85, 92, 78]; echo count($scores); -
Match each function to its purpose
- count()
- Element count
- sizeof()
- Same as count()
- COUNT_RECURSIVE
- Nested counting
-
What is the index of the last element in a five-element array?
$items = [10, 20, 30, 40, 50];- 5
- count($items)
- 4
- 1
Show answer
4 — Correct. For five elements the indexes are 0-4; the last is 4 = count-1.