Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How to count number of elements in an array

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 123
    Comment on it

    There are two PHP functions count() and sizeof() which can be used to count the number of elements of an array. Both functions can also be used to count the number of elements of multi-dimensional array also. The explanation of these functions are given below :


    1. count() : count() function takes an array as argument and returns the count of elements of an array.

    Syntax : count (array, count_mode)

    Description :

    array : Specifies the array whose element has to count (Required).

    count_mode : Specify the mode for counting elements in an array (Optional).

    The possible values can be used for count_mode are :

    • 0 (COUNT_NORMAL) : This is the default mode, using this code the function does not count all elements of multi-dimensional array.
    • 1 (COUNT_RECURSIVE) : In this mode count() recursively count the array elements. This mode can be used for counting elements of multi-dimensional array.

    Note : If the first argument has no value or an empty array than function returns 0. If first argument variable is not an array than it returns 1.


    Example :

    <?php
    $cities = array(
     "India" => array("Delhi", "Mumbai"),
     "USA" => array("NewYork", "Alaska"),
     "Thailand" => array("Bangkok", "Phuket", "Kirabi")    
    );
    echo "Normal Count : ".count($cities);
    echo "<br>";
    echo "Recursive Count : ".count($cities, 1);
    
    $var = TRUE; //boolean variable
    echo "Count : ".count($var);
    ?>
    

    Output :
    Normal Count : 3
    Recursive Count : 10
    Count : 1


    2. sizeof() : sizeof() function is an alias of count(). It also used to count the number of elements of an array.

    Syntax : sizeof(array, count_mode)

    Description : The arguments are same as used in count().

    Example :

    <?php
    $cities = array(
     "India" => array("Delhi", "Mumbai"),
     "USA" => array("NewYork", "Alaska"),
     "Thailand" => array("Bangkok", "Phuket", "Kirabi")    
    );
    echo "Normal count : ".sizeof($cities);
    echo "<br>";
    echo "Recursive count : ".sizeof($cities, 1);
    ?>
    

    Output :
    Normal count : 3
    Recursive count : 10


 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: