When working with arrays in PHP, it is important to know the number of elements in an array. PHP provides simple built-in functions like count() and sizeof() to find the array length quickly. In this tutorial, you will learn how to use these functions with examples. Understanding how to count array elements in PHP will help you manage arrays more effectively in your applications.
See the code below for count() function:
<?php
$languages = array('Basic','Pascal','PHP','Python','Java');
$count = count($languages);
echo $count;
Here, $languages is a PHP array and we are using count() function on the array. In this case, the output will be 5.
You can also use the sizeof() function in place of count(). See the code below for sizeof() function:
<?php
$numbers = array(5,10,15,20,25,30);
$count = sizeof($numbers);
echo $count;
In this case, the output will be 6. Both count() and sizeof() give the same result; count() is a more commonly used function in PHP for this purpose.
Now, we want to read each element of an array using a loop and display the count of the array elements at the end. We will use PHP code with HTML below and display the output in the browser:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Count elements of an Array in PHP</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
</head>
<body>
<div class="container" style="text-align: center;font-size: 20px;">
<h3>Find number of elements of an Array</h3>
<?php
$languages = array('Basic','Pascal','PHP','Python','Java');
// Display all array element first
echo "Array elements are: <br>";
foreach ($languages as $value) {
echo "$value<br>";
}
// get count of elements
$count = count($languages);
echo "No. of elements in the array is: <strong>".$count."</strong>";
?>
</div>
</body>
</html>
We are displaying the array elements and then the count. By using count($languages), we get the number of elements in the array. Let us save this file as index.php under xampp/htdoc/array folder.
If you run this in the browser using localhost/array, you will see the below output:
Post a Comment