Horje
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

  • 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
// 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



Reffered: https://www.geeksforgeeks.org


PHP

Related
How to use the printf() Function in PHP ? How to use the printf() Function in PHP ?
How to check if a String contains a Specific Character in PHP ? How to check if a String contains a Specific Character in PHP ?
How to sort an associative array by key in PHP? How to sort an associative array by key in PHP?
How the User-Defined Function differs from Built-in Function in PHP ? How the User-Defined Function differs from Built-in Function in PHP ?
What is use of the json_encode() and json_decode() functions in PHP? What is use of the json_encode() and json_decode() functions in PHP?

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
12