使用 count() 函数
计算数组中的所有当前元素。
在空数组的情况下,它将返回 0。
语法如下所示:
count($array, mode)
如果可选的 mode 参数设置为 COUNT_RECURSIVE(或者 1),count() 将递归计算数组内部的元素数。
这对于计算多维数组的所有元素特别有用。
这是一个例子:
<?php //PHP program for counting all the elements //or values inside an array //Using the count() function $array = [ "onitroad1", "onitroad2", "onitroad3", "1", "2", "3" ]; echo "Count first array elements: " . count($array) . "\n"; $array = [ 'names' => [ "onitroad1", "onitroad2", "onitroad3" ], 'rank' => [ '1', '2', '3' ] ]; echo "Recursive count: " . count($array, ) . "\n"; echo "Normal count: " . count($array, ); ?>
使用 count() 函数后,我们将获得以下输出:
Count first array elements: 6 Recursive count: 8 Normal count: 2
假设我们有一个包含多个元素的数组,我们需要借助 PHP 计算所有元素。
使用 sizeof() 函数
此函数用于计算数组或者其他可数对象中元素的数量。
此函数使用的语法如下:
sizeof($array, mode)
Sizeof() 是 count() 的别名。
更准确地说,让我们看一个例子:
<?php //使用 sizeof() 函数计算数组中所有元素或者值 $array = [ "onitroad1", "onitroad2", "onitroad3", "1", "2", "3" ]; echo "Count second array elements: " . sizeof($array) . "\n"; $array = [ 'names' => [ "onitroad1", "onitroad2", "onitroad3" ], 'rank' => [ '1', '2', '3' ] ]; echo ("Recursive count: " . sizeof($array, ) . "\n"); echo ("Normal count: " . sizeof($array, ) . "\n"); ?>
使用 sizeof() 函数后,我们将获得以下输出:
Count second array elements: 6 Recursive count: 8 Normal count: 2
日期:2020-06-02 22:15:47 来源:oir作者:oir