How to find the number of elements in an array in PHP

Counting the elements in an array gives the length of the array. You can find the number of elements in an array using PHP function count($array), where $array is a PHP array.

In this topic, I will show how you can use PHP count() function on an array and display the number of elements in the array. See the below code:


<?php
    $languages = array('Basic','Pascal','PHP','Python','Java');
    $count = count($languages);
    echo $count;

Here, $languages is a PHP array and we are using count() function on the array. In this case, the output will be 5.

Take a look at the below code, we want to display output in the browser:


<!DOCTYPE html>
<html lang="en">
<head>
  <title>Count elements of an Array in PHP</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
</head>
<body>
  <div class="container" style="text-align: center;font-size: 20px;">
    <h3>Find number of elements of an Array</h3>
    <?php
    $languages = array('Basic','Pascal','PHP','Python','Java');
    // Display all array element first
    echo "Array elements are: <br>";
    foreach ($languages as $value) {
      echo "$value<br>";
    }
    // get count of elements
    $count = count($languages);
    echo "No. of elements in the array is: <strong>".$count."</strong>";
    ?>
  </div>
</body>
</html>

We are displaying the array elements and then displaying the count. By using count($languages), we get the number of elements in the array. Let us save this file as index.php under xampp/htdoc/array folder.

If you run this in the browser using localhost/array, you will see below output:

count number of elements in an array in php

count number of elements in an array in phpConclusion

This is an example of using array function in PHP. While coding, specially, during string manipulation, you might have to use various PHP functions on strings and arrays. Finding array length or number of elements in an array is very common while coding in PHP.