Counting the elements in an array gives the length of the array. You can find the number of elements in an array using the PHP function count($array)
, where $array is a PHP array.
In this topic, I will show how to use the PHP count()
function on an array and display the number of elements in the array. See the below code:
<?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.
Take a look at the below code, we want to 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