Open In App

How to Find Array Length in PHP ?

In PHP, determining the length or size of an array is a common operation, especially when dealing with data structures such as arrays. The length of an array represents the total number of elements it contains. PHP provides several methods to find the length of an array, allowing developers to perform various array-related operations efficiently.

Approach

Syntax

// Using count() function
$length = count($array);
// Using sizeof() function (alias of count())
$length = sizeof($array);

Example: Implementation to find array length.




<?php
// Define an array
$array = [1, 2, 3, 4, 5];
 
// Using count() function
$length = count($array);
echo "The length of the array is: $length";
echo "\n";
 
// Using sizeof() function
$length = sizeof($array);
echo "The length of the array is: $length";
 
?>

Output
The length of the array is: 5
The length of the array is: 5




Difference between count() and sizeof() Methods

count() Function sizeof() Function
Returns the total number of elements in an array Alias of the count() function, behaves identically to count()
Widely used for counting array elements in PHP Provided as an alternative function to count(), primarily for backward compatibility
Recommended for use in current PHP codebases May be deprecated in future PHP versions
Article Tags :