We have given an array containing some array elements and the task is to count all elements of an array arr using PHP. In order to do this task, we have the following methods in PHP:
Approach 1: Using count() Method: The count() method is used to count the current elements in an array. It returns 0 for an empty array.
Syntax:
count($array, mode)
Example :
PHP
<?php
$array = array ( "Geek1" , "Geek2" ,
"Geek3" , "1" , "2" , "3" );
echo "Count first array elements: " . count ( $array ) . "\n" ;
$array = array (
'names' => array ( "Geek1" , "Geek2" , "Geek3" ),
'rank' => array ( '1' , '2' , '3' )
);
echo "Recursive count: " . count ( $array , 1) . "\n" ;
echo "Normal count: " . count ( $array , 0);
?>
|
Output
Count first array elements: 6
Recursive count: 8
Normal count: 2
Approach 2: Using sizeof() Method: The sizeof() method is used to count the number of elements present in an array or any other countable object.
Syntax:
sizeof($array, mode)
Example :
PHP
<?php
$array = array ( "Geek1" , "Geek2" ,
"Geek3" , "1" , "2" , "3" );
echo "Count second array elements: "
. sizeof( $array ) . "\n" ;
$array = array (
'names' => array ( "Geek1" , "Geek2" , "Geek3" ),
'rank' => array ( '1' , '2' , '3' )
);
echo ( "Recursive count: " . sizeof( $array , 1) . "\n" );
echo ( "Normal count: " . sizeof( $array , 0) . "\n" );
?>
|
Output
Count second array elements: 6
Recursive count: 8
Normal count: 2
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
01 Jun, 2020
Like Article
Save Article