How to Find Array Length in PHP ?
Last Updated :
13 Feb, 2024
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
- Using count() Function: The
count()
function is a built-in PHP function used to count the number of elements in an array. It returns the total count of elements within the array.
- Using sizeof() Function: The
sizeof()
function is an alias of the count()
function in PHP. It behaves identically count()
and can be used interchangeably.
Syntax
// Using count() function
$length = count($array);
// Using sizeof() function (alias of count())
$length = sizeof($array);
Example: Implementation to find array length.
PHP
<?php
$array = [1, 2, 3, 4, 5];
$length = count ( $array );
echo "The length of the array is: $length" ;
echo "\n" ;
$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 |
Share your thoughts in the comments
Please Login to comment...