How to Get Array Length in PHP Using count() and sizeof()
This article explains how to determine the length of one‑dimensional and multi‑dimensional arrays in PHP using the count() and sizeof() functions, shows code examples, discusses the two optional parameters of count(), and provides guidance on handling empty or undefined arrays.
PHP provides two built‑in functions, count and sizeof, to obtain the number of elements in a one‑dimensional array. Both functions return the same result because sizeof is simply an alias of count.
Basic usage examples:
$arr = array('0','1','2','3','4');
echo count($arr); // outputs 5
$arr = array('A','B','C');
echo sizeof($arr); // outputs 3Both functions also work with empty arrays or undefined variables, returning 0 in those cases.
When dealing with multi‑dimensional arrays, the count function accepts a second parameter to control recursion: COUNT_NORMAL (or 0) – counts only the top‑level elements. COUNT_RECURSIVE (or 1) – counts elements in nested arrays as well.
Example of a two‑dimensional array and counting its elements:
<?php
$arr = array(
0 => array('title' => 'News1', 'viewnum' => 123, 'content' => 'ZAQXSWedcrfv'),
1 => array('title' => 'News2', 'viewnum' => 99, 'content' => 'QWERTYUIOPZXCVBNM')
);
?>Counting only the top‑level entries (the two news items):
echo 'Not counting sub‑arrays: ' . count($arr, COUNT_NORMAL); // outputs 2Counting all elements recursively:
echo 'Counting sub‑arrays: ' . count($arr, COUNT_RECURSIVE); // outputs 8These examples demonstrate how to choose the appropriate function and parameter based on whether you need to include nested array elements in the count.
In summary, count() and sizeof() provide flexible ways to obtain array lengths in PHP, with optional recursion for multi‑dimensional structures.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
php Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
