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:
<code>$arr = array('0','1','2','3','4');
echo count($arr); // outputs 5
$arr = array('A','B','C');
echo sizeof($arr); // outputs 3</code>Both 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:
<code><?php
$arr = array(
0 => array('title' => 'News1', 'viewnum' => 123, 'content' => 'ZAQXSWedcrfv'),
1 => array('title' => 'News2', 'viewnum' => 99, 'content' => 'QWERTYUIOPZXCVBNM')
);
?></code>Counting only the top‑level entries (the two news items):
<code>echo 'Not counting sub‑arrays: ' . count($arr, COUNT_NORMAL); // outputs 2</code>Counting all elements recursively:
<code>echo 'Counting sub‑arrays: ' . count($arr, COUNT_RECURSIVE); // outputs 8</code>These 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.
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.