count()
方法“ count()函数”用于获取数组元素的总数。
语法:
count(array, [count_mode])
这里,
array是输入数组的名称
count_mode是一个可选参数,默认值为0,它具有两个值
0 –不对多维数组的
所有元素进行计数1 –对多维数组的所有元素进行计数
例子:
Input: $arr1 = array("101", "102", "103", "104", "105"); Output: arr1 has 5 elements
PHP代码:使用一维数组
<?php $arr1 = array("101", "102", "103", "104", "105"); $arr2 = array("Amit", "Abhishek", "Prerana", "Aleesha", "Prem"); $len = count($arr1); print ("arr1 has $len elements\n"); $len = count($arr2); print ("arr2 has $len elements\n"); ?>
输出结果
arr1 has 5 elements arr2 has 5 elements
PHP代码:使用多维数组
<?php $students = array( "101" => array( "name" => "Amit", "age" => 21, ), "102" => array( "name" => "Abhi", "age" => 20, ) ); $len = count($students); print ("count value = $len (count_mode is not provided)\n"); $len = count($students, 0); print ("count value = $len (count_mode is set to 0)\n"); $len = count($students, 1); print ("count value = $len (count_mode is set to 1)\n"); ?>
输出结果
count value = 2 (count_mode is not provided) count value = 2 (count_mode is set to 0) count value = 6 (count_mode is set to 1)