Home Tutorial Php Phpbasics PHP Array Count

 
 

PHP Array Count
Posted on: October 24, 2009 at 12:00 AM
PHP Array Count: In this tutorial you will come to know about counting the number of elements of an array, it describes the count() and sizeof() functions, examples will illustrate these functions,

PHP Array Count Function

To count the elements of an array PHP provides count() function. It counts all elements of an array or properties of an object.

The count() and sizeof() functions are identical. There is no such difference between these two functions. 

General Format int count( 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

 PHP Array Count Function 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=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);

$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 2 (Same as previous with sizeof() function):

<?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/>";

?>

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 

 

 

Related Tags for PHP Array Count:


Ask Questions?

If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.

Ask your questions, our development team will try to give answers to your questions.