Does PHP have a built in function that will allow me to find the size of a 2D array without having to first having to loop through the array and hitting a NULL (C style)
When i say size i mean the number or rows in a 2D array.
many thanks,
Does PHP have a built in function that will allow me to find the size of a 2D array without having to first having to loop through the array and hitting a NULL (C style)
When i say size i mean the number or rows in a 2D array.
many thanks,
Nice catch by — sizeof() does the job because it is simply an alias of count(). For an array-of-arrays (a typical "2D array" in PHP) the top-level count() returns the number of rows directly, so there is no need for a manual loop. See the PHP manual for details on count() and the COUNT_RECURSIVE option: PHP manual - count().
Common follow-ups and patterns not shown above by :
$rows = count($data);
$first = reset($data);
$cols = is_array($first) ? count($first) : 0;
$totalInner = array_sum(array_map('count', $data));
// or using recursion:
$totalRecursive = count($data, COUNT_RECURSIVE);
// note: $totalRecursive == $rows + $totalInner Use count($data) for row count. Use array_map('count', $data) (then array_sum) when you need the total number of inner elements, or count($data, COUNT_RECURSIVE) if you want a recursive count (remember that recursive count includes the top-level rows too).
Compatibility and gotchas: validate the variable before counting on older PHP versions to avoid warnings—use is_countable() (PHP 7.3+) or is_array()/instanceof Countable on older installs. Also note rows can be "ragged" (different column counts), so choose per-row counts if column uniformity matters. Links: PHP manual - is_countable().
have solved my own question:
use sizeof() function.
:)
Dear friend
$value= array(2,5,6,8,9);
echo "size of array = ".sizeof($value)."<br>"; // Output = 5
Thanks and Regards
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.