PHP Array Sizeof: This tutorial will help you to learn sizeof() function, which is similar to count() function, it returns the number of elements present in an array. The examples of this tutorial will help you to understand this function in better way.
PHP Array Sizeof: This tutorial will help you to learn sizeof() function, which is similar to count() function, it returns the number of elements present in an array. The examples of this tutorial will help you to understand this function in better way.PHP Array sizeof() function
To count the elements of an array PHP provides sizeof() function. It counts all elements of an array or properties of an object.
The sizeof() & count() functions are identical. There is no such difference between these two functions.
General Format | int sizeof( mixed $array [,int mode]) | |
Parameters | $array: the array to be count | mode: 0 (by default)
or 1 for COUNT_RECURSIVE
|
Return Value | Returns the number of elements in array |
Example 1:
<?php
$a[0]=0;
$a[8]=1;
$a[2]=2;
echo"<br/><b>Elements of the \$a is:</b><br/>";
print_r($a);
$count=sizeof($a);
echo"<br/><b>Total no of elements present in \$a is:</b>".$count."<br/>";
$b=array(0=>0,3=>4);
print_r($b);
$count=sizeof($b);
echo"<br/><b>Total no of elements present in \$b is:</b>".$count."<br/>";
?>
Elements of the $a is:
Array
(
[0] => 0
[8] => 1
[2] => 2
)
Total no of elements present in $a is:3
Array
(
[0] => 0
[3] => 4
)
Total no of elements present in $b is:2
Example 2 (Same example with count() fucntion):
<?php
$a[0]=0;
$a[8]=1;
$a[2]=2;
echo"<br/><b>Elements of the \$a is:</b><br/>";
print_r($a);
$count=count($a);
echo"<br/><b>Total no of elements present in \$a is:</b>".$count."<br/>";
$b=array(0=>0,3=>4);
print_r($b);
0$count=count($b);
echo"<br/><b>Total no of elements present in \$b is:</b>".$count."<br/>";
?>
Output:
Elements of the $a is: Array ( [0] => 0 [8] => 1 [2] => 2 ) Total no of elements present in $a is:3 Array ( [0] => 0 [3] => 4 ) Total no of elements present in $b is:2
Example 3 (Multi-Dimensional Array):
<?php
$leisure=array('song'=>array('ghazal','rap','classical'),
'sport'=>array('cricket','football','chess'));
echo "<br/><b>The elements of the array is :</b><br/>";
var_dump($leisure);
echo "<br/><b>Total no of element (normal count) is :</b>".count($leisure);
echo "<br/><b>Total no of element (recursive count) is :</b>". sizeof($leisure,COUNT_RECURSIVE);
?>
Output:
The elements of the array is : array(2) { ["song"]=> array(3) { [0]=> string(6) "ghazal" [1]=> string(3) "rap" [2]=> string(9) "classical" } ["sport"]=> array(3) { [0]=> string(7) "cricket" [1]=> string(8) "football" [2]=> string(5) "chess" } } Total no of element (normal count) is :2 Total no of element (recursive count) is :8