如何在 PHP 中计算数组的所有元素?

2024 年 8 月 29 日 | 阅读 2 分钟

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

例如

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

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

输出

Number of elements present in the array: 4

示例 2

输出

Number of elements present in the array: 8

示例 3:使用 sizeof() 进行计数

输出

Number of elements present in the array: 6

示例 4

输出

Number of elements present in the array: 7

示例 5:使用二维数组的示例

输出

8
8