php输出数组所有元素,如何计算PHP数组中的所有元素?

这篇博客介绍了PHP中用于计算数组元素数量的内置函数count()和sizeof()。通过多个示例展示了如何使用这两个函数来获取一维和二维数组的元素个数,输出结果均为数组元素的总数。示例涵盖了不同类型的数据和数组结构。
摘要由CSDN通过智能技术生成

为了计算数组中的所有元素, PHP提供了count()和sizeof()函数。 count()和sizeof()这两个函数都用于对数组中的所有元素进行计数, 并为已用空数组初始化的变量返回0。这些是PHP的内置函数。我们可以使用count()或sizeof()函数来计算数组中存在的元素总数。

例如

我们将使用count()和sizeof()方法讨论所有数组元素的程序实现。

示例1:使用count()进行计数

$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

$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()进行计数

$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

$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:使用2D数组的示例

$snacks = array('drinks' => array('cold coffee', 'traffic jam', 'Espresso', 'Americano'), 'bevrage' => array('spring rolls', 'nuddles'));

echo count($snacks, 1);

echo "";

echo sizeof($snacks, 1);

?>

输出

8

8

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值