isset,array_key_exists和!empty的解决方法 [英] Workaround for isset, array_key_exists and !empty
问题描述
在编写php时,我尝试避免尽可能多的警告。关于数组,现在有一个问题困扰着我很多时间。
When coding php I try to avoid as many warnings as possible. There is one question that bugs me for quite some time now, regarding arrays.
在处理数组及其值时,我经常先检查空值,然后再进行实际工作。
When working with arrays and their values I often check for empty values first before I go to the "real work".
if(array_key_exists('bla', $array){
if( !empty($array['bla']) {
# do something
}
}
我的问题是:
这是很多代码,用于检查我是否可以使用值。是否有一些更短的方法可以检查数组中的值,或可能不存在?
This is a lot of code for just checking if I have values to work with. Is there some shorter way to check a value within an array that may or may not exist?
推荐答案
不要使用 空
,除非您确定就是您想要的:
Don't use empty
unless you are sure that's what you want:
如果
var
存在并且具有非空,非空值,则返回FALSE
-零值,否则返回TRUE
。
Returns
FALSE
ifvar
exists and has a non-empty, non-zero value. Otherwise returnsTRUE
.
以下内容被认为是空的:
The following things are considered to be empty:
-
-
0
(0为整数) -
0.0
(0为浮点数) -
0
(0作为字符串) -
NULL
-
FALSE
-
array()
(空数组) -
$ var;
(已声明变量,但没有值)
""
(an empty string)0
(0 as an integer)0.0
(0 as a float)"0"
(0 as a string)NULL
FALSE
array()
(an empty array)$var;
(a variable declared, but without a value)
该手册没有明确列出如果 var
不存在情况,但这是几个:
The manual doesn't explicitly list the "if var
doesn't exist" cases, but here are a couple:
-
$ array ['undeclaredKey']
(现有数组,但未声明键) -
$ undeclaredVar;
(未声明变量)
$array['undeclaredKey']
(an existing array, but key not declared)$undeclaredVar;
(a variable not declared)
通常, array_key_exists
检查就足够了。
Usually the array_key_exists
check should suffice.
这篇关于isset,array_key_exists和!empty的解决方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!