PHP比较数组、对象是否为空

PHP简单对比对象、数组是不是为空:

 1 <?php
 2 /*简单的比较对象和数组是不是为空*/
 3 
 4 #定义空类EmptyClass
 5 class EmptyClass{}
 6 
 7 $emptyClass = new EmptyClass(); #实例化空类
 8 $stdClass = new stdClass(); #实例化stdClass,一个php的内部保留类;没有属性和方法的空类;
 9 $array = array(); #定义空数组
10 
11 #第一种方法用empty()函数进行判定.
12 if(empty($emptyClass)){
13     echo "$emptyClass is empty."; #预期输出
14 }else{
15     echo "$emptyClass is not empty."; #不是预期的
16 }
17 #输出结果为:$emptyClass is not empty.这不是预期输出,在预期里应该是空类;
18 echo "<br>";
19 
20 if(empty($stdClass)){
21     echo "$stdClass is empty."; #预期输出
22 }else{
23     echo "$stdClass is not empty."; #不是预期的
24 }
25 #输出结果为:$stdClass is not empty.不是预期的,保留类,空的,但是可以向其中添加属性;
26 echo "<br>";
27 
28 if(empty($array)){
29     echo "$array is empty."; #预期输出
30 }else{
31     echo "$array is not empty."; #不是预期的
32 }
33 #输出结果为:$array is empty.符合预期;
34 echo "<br>";
35 
36 #第二种方法用count()函数来判定一下;
37 echo "EmptyClass Count: " . count($emptyClass); #输出1;
38 echo "<br>";
39 echo "std Class Count: " . count($stdClass); #输出1;
40 echo "<br>";
41 echo "array count: " . count($array); #输出0;
42 echo "<br>";
43 
44 
45 #第三种方法自定义函数进行判定
46 function getCount($var){
47     $count = 0; #统计次数初始值为0
48     #条件开始,首先要判定是不是数组或者对象;
49     if(is_array($var) || is_object($var)){
50         #开始循环数组或者对象
51         foreach ($var as $key=>$value){
52             $count ++; #计数在每次循环后自增1;
53         }
54     }
55     unset($var); #在内存中是释放变量;
56     return $count; #返回统计次数;
57 }
58 #调用函数进行判定
59 if(getCount($emptyClass) === 0){
60     echo "$emptyClass is empty."; #预期输出
61 }else{
62     echo "$emptyClass is not empty."; #不是预期输出
63 }
64 #输出$emptyClass is empty.符合预期;
65 echo "<br>";
66 if(getCount($stdClass) === 0){
67     echo "$stdClass is empty."; #预期输出
68 }else{
69     echo "$stdClass is not empty."; #不是预期输出
70 }
71 
72 echo "<br>";
73 if(getCount($array) === 0){
74     echo "$array is empty."; #预期输出
75 }else{
76     echo "$array is not empty."; #不是预期输出
77 }
78 echo "<br>";
79 ?>

代码没有意义,仅供学习交流。

原文地址:https://www.cnblogs.com/mafu/p/13502297.html