个性化阅读
专注于IT技术分析

如何计算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:使用2D数组的示例

<?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

赞(0)
未经允许不得转载:srcmini » 如何计算PHP数组中的所有元素?

评论 抢沙发

评论前必须登录!