Search code snippets, questions, articles...

Length of array PHP

$fruits = array("banana", "apple", "orange");
echo count($fruits);
Best JSON Validator, JSON Tree Viewer, JSON Beautifier at same place.

You can get the length of an array in PHP by using count function. In the code snippet, we are counting $fruits variable values.

    $subject = [
        "name" => "Math",
        "code" => "MT01",
        "enrolls" => "20"
    echo sizeof($subject);
    // -> 3
You can also get the length of a PHP array using sizeof() method. You need to pass your array to sizeof(array) method and it will return you the length of the array.
        "name" => "Math",
        "students" => ["John", "Rick", "Diana"],
        "classes" => [10, 12]
    echo sizeof($subject, 1);
You can use sizeof() method of PHP to calculate the length of a multidimensional array. You just need to pass the second parameter of sizeof(PHP_ARRAY, RECURSIVE) method to 1. In the above code snippet, we have an array that contains three items. But the items of the array also contain arrays with multiple items. If you wanna calculate the length of all the items in the array just use - sizeof($array, 1).
Was this helpful?