PHP - Counting Elements in an Array

Introduction

To find out how many elements are in an array, use PHP's count() function.

Demo

<?php

         $authors = array("A","B","C","D");
         $myBook = array("title" => "Java",
                        "author"=> "John A",
                        "pubYear"=>  2018);

         echo count($authors)."\n"; // Displays"4"
         echo count($myBook)."\n";  // Displays"3"
?>/*from   w  w w  . ja  v  a 2s  . c o  m*/

Result

To use count() to retrieve the last element of an indexed array:

Demo

<?php

         $authors = array("A","B","C","D");
         $lastIndex = count($authors)-1;
         echo $authors[$lastIndex]; // Displays"D"
?>//ww  w . j  a  v a 2s.c o  m

Result

An indexed array with four elements doesn't mean that the last element has an index of 3!

Consider the following example:

Demo

<?php

            // Create a sparse indexed array
            $authors = array(0 => "A", 1 => "B", 2=> "C", 47 =>"D");
            $lastIndex = count($authors)-1;
            echo $authors[$lastIndex]; // Generates an"Undefined offset"notice
?>//w ww.  ja va  2  s .  c  om

Result

$authors array's highest index is 47, the array contains four elements, not 48.

These types of arrays are often called sparse arrays.

Related Topic