如何在PHP中获取数组单元数量

 2622

6077b3a5137da.png


PHP中为了获取数组单元数量或者对象的属性个数,提供了count()函数,同时count()的别名被称为sizeof(),二者没有什么区别。首先,先介绍一下一下count()函数的语法。

语法:

count ( mixed $array  , int $mode )

$array:数组或者 Countable 对象。

$mode:(可选)$mode 参数设为 COUNT_RECURSIVE(或 1),count() 将递归地对数组计数。

返回值:单元数目。如果参数既不是数组,也不是实现 Countable 接口的对象,将返回 1。 如果$array是 null 则返回0。


使用示例:

1、获取数组单元数量:

<?php
    $a[0] = 1;
    $a[1] = 3;
    $a[2] = 5;
    var_dump(count($a));
     
    var_dump(count(null));
    var_dump(count(false));
?>

输出结果:

int(3)
Warning: count(): Parameter must be an array or an object that ..//PHP 7.2 起int(0)
Warning: count(): Parameter must be an array or an object that ...// PHP 7.2 起int(1)


2.对象的属性个数

<?php
class C implements Countable {
     public function count() {
         return 0;
     }
 }
 
 $a = [];
 var_dump($a);
 echo 'array is empty: '; var_dump(empty($a));
echo"<br>";
 $c = new C;
 var_dump($c);
 echo"<br>";
 echo 'Countable is empty: ' ; var_dump(empty($c));
 echo"<br>";
 ?>

输出结果:

array(0) { } array is empty: bool(true)
object(C)#1 (0) { }
Countable is empty: bool(false)


TAG标签:
本文网址:https://www.zztuku.com/detail-8794.html
站长图库 - 如何在PHP中获取数组单元数量
申明:如有侵犯,请 联系我们 删除。

评论(0)条

您还没有登录,请 登录 后发表评论!

提示:请勿发布广告垃圾评论,否则封号处理!!

    编辑推荐

    MAC环境配置定时任务