PHP 如何统计数组中的所有元素
要统计数组中的所有元素,PHP提供了count()和sizeof()函数。count()和sizeof()函数都用于统计数组中的所有元素,并对已初始化为空数组的变量返回0。这些是PHP的内置函数。我们可以使用count()或sizeof()函数来统计数组中的总元素数。
例如:
我们将讨论使用count()和sizeof()方法来实现对数组所有元素的计数。
示例1 :使用count()进行计数
<?php
ele = array("Ryan", "Ahana", "Ritvik", "Amaya");no_of_ele = count(ele);
echo "Number of elements present in the array: ".no_of_ele;
?>
输出
Number of elements present in the array: 4
示例2
<?php
ele = array(14, 89, 26, 90, 36, 48, 67, 75);no_of_ele = sizeof(ele);
echo " Number of elements present in the array: ".no_of_ele;
?>
输出
Number of elements present in the array: 8
示例3 :使用sizeof()函数进行计数
<?php
ele = array("Jan", "Feb", "Mar", "Apr", "May", "Jun");no_of_ele = sizeof(ele);
echo " Number of elements present in the array: ".no_of_ele;
?>
输出
Number of elements present in the array: 6
示例4
<?php
ele = array(14, 89, 26, 90, 36, 48, 67);no_of_ele = sizeof(ele);
echo " Number of elements present in the array: ".no_of_ele;
?>
输出
Number of elements present in the array: 7
示例5 :使用二维数组的示例
<?php
snacks = array('drinks' => array('cold coffee', 'traffic jam', 'Espresso',
'Americano'), 'bevrage' => array('spring rolls', 'nuddles'));
echo count(snacks, 1);
echo "</br>";
echo sizeof($snacks, 1);
?>
输出
8
8