Google News
logo
PHP Program to count() - Return the length of an array
In the following example of PHP program that demonstrates how to use the `count()` function to return the length of an array :
Program :
<?php

// Create an indexed array
$fruits = array("apple", "banana", "orange", "kiwi");

// Print the length of the array
echo "The length of the fruits array is: " . count($fruits) . "<br>";

// Create an associative array
$ages = array("John" => 25, "Mary" => 30, "Bob" => 35);

// Print the length of the array
echo "The length of the ages array is: " . count($ages) . "<br>";

?>
Output :
The length of the fruits array is: 4
The length of the ages array is: 3
In this example, we have used the `count()` function to return the length of two different arrays. The first array is an indexed array `$fruits` with four elements. We pass this array to the `count()` function, which returns the number `4`.

The second array is an associative array `$ages` with three elements. We pass this array to the `count()` function, which returns the number `3`.

The `count()` function is a built-in function in PHP that can be used to return the number of elements in an array. It works with both indexed and associative arrays.