0
0
PHPprogramming~5 mins

Array count and length in PHP

Choose your learning style9 modes available
Introduction

We use array count and length to find out how many items are inside an array. This helps us understand the size of the array.

When you want to know how many friends are in your friends list stored in an array.
When you need to loop through all items in a shopping cart array.
When you want to check if an array is empty before using it.
When you want to display the number of messages in an inbox array.
Syntax
PHP
<?php
// Define an array
$array = [1, 2, 3, 4];

// Get the number of elements
$count = count($array);

// Print the count
echo $count;
?>

Use the count() function to get the number of elements in an array.

PHP arrays do not have a separate length property like some other languages; use count() instead.

Examples
Counting an empty array returns 0.
PHP
<?php
// Empty array
$emptyArray = [];
echo count($emptyArray); // Output: 0
?>
Counting an array with one item returns 1.
PHP
<?php
// Array with one element
$singleElementArray = ['apple'];
echo count($singleElementArray); // Output: 1
?>
Counting an array with three items returns 3.
PHP
<?php
// Array with multiple elements
$fruits = ['apple', 'banana', 'cherry'];
echo count($fruits); // Output: 3
?>
Counting an associative array counts the number of key-value pairs.
PHP
<?php
// Associative array
$person = ['name' => 'John', 'age' => 30];
echo count($person); // Output: 2
?>
Sample Program

This program shows how to count elements in an array before and after adding a new item.

PHP
<?php
// Create an array of colors
$colors = ['red', 'green', 'blue'];

// Print the array before counting
echo "Colors array before counting:\n";
print_r($colors);

// Get the count of elements
$numberOfColors = count($colors);

// Print the count
echo "Number of colors: $numberOfColors\n";

// Add a new color
$colors[] = 'yellow';

// Print the array after adding
echo "Colors array after adding a new color:\n";
print_r($colors);

// Get the new count
$numberOfColors = count($colors);

// Print the new count
echo "Number of colors now: $numberOfColors\n";
?>
OutputSuccess
Important Notes

The count() function runs in O(1) time because PHP stores the size internally.

Memory use is minimal since count() does not copy the array.

A common mistake is to try to use sizeof() as a property; it is a function like count().

Use count() when you need the number of elements; use loops or other functions to access elements.

Summary

count() tells you how many items are in an array.

It works for empty, single, multiple, and associative arrays.

Use it before looping or when you need to check if an array has items.