如何检查 PHP 数组是否设置了任何值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1371198/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to check if a PHP array has any value set?
提问by JasonDavis
I am working on a signup form, I am using PHP and on my processing part I run some code, if a submitted item fails I then add it to an errors array.
我正在处理一个注册表单,我正在使用 PHP,在我的处理部分我运行一些代码,如果提交的项目失败,我会将它添加到一个错误数组中。
Below is a snip of the code, I am at the point where I need to find the best method to determine if I should trigger an error.
下面是代码片段,我现在需要找到最佳方法来确定是否应该触发错误。
So if there is a value set in the error array then I need to redirect and do some other stuff.
所以如果在错误数组中设置了一个值,那么我需要重定向并做一些其他的事情。
I was thinking of using issetor else is_arraybut I don't think that is the answer since I set the array using **$signup_errors = array()**wouldn't this make the is_arraybe true?
我正在考虑使用isset否则,is_array但我认为这不是答案,因为我使用设置数组**$signup_errors = array()**不会使结果is_array成为真的吗?
Can anyone suggest a good way to do this?
谁能建议一个好的方法来做到这一点?
//at the beginning I set the error array
$signup_errors = array();
// I then add items to the error array as needed like this...
$signup_errors['captcha'] = 'Please Enter the Correct Security Code';
回答by cletus
if ($signup_errors) {
// there was an error
} else {
// there wasn't
}
How does it work? When converting to boolean, an empty array converts to false. Every other array converts to true. From the PHP manual:
它是如何工作的?转换为布尔值时,空数组将转换为 false。每隔一个数组都会转换为 true。从PHP 手册:
Converting to boolean
To explicitly convert a value to boolean, use the (bool) or (boolean) casts. However, in most cases the cast is unncecessary, since a value will be automatically converted if an operator, function or control structure requires a boolean argument.
See also Type Juggling.
When converting to boolean, the following values are considered FALSE:
- the boolean FALSE itself
- the integer 0 (zero)
- the float 0.0 (zero)
- the empty string, and the string "0"
- an array with zero elements
- an object with zero member variables (PHP 4 only)
- the special type NULL (including unset variables)
- SimpleXML objects created from empty tags
- Every other value is considered TRUE (including any resource).
转换为布尔值
要将值显式转换为布尔值,请使用 (bool) 或 (boolean) 强制转换。然而,在大多数情况下,强制转换是不必要的,因为如果运算符、函数或控制结构需要布尔参数,值将被自动转换。
另请参阅类型杂耍。
转换为布尔值时,以下值被视为 FALSE:
- 布尔值 FALSE 本身
- 整数 0(零)
- 浮点数 0.0(零)
- 空字符串和字符串“0”
- 一个元素为零的数组
- 具有零成员变量的对象(仅限 PHP 4)
- 特殊类型 NULL(包括未设置的变量)
- 从空标签创建的 SimpleXML 对象
- 每隔一个值都被认为是 TRUE(包括任何资源)。
You could also use empty()as it has similar semantics.
您也可以使用empty()它,因为它具有类似的语义。
回答by gnarf
Perhaps empty()?
也许是空的()?
From Docs:
从文档:
Return Values
Returns FALSE if var has a non-empty and non-zero value.
The following things are considered to be empty:
"" (an empty string) 0 (0 as an integer) "0" (0 as a string) NULL FALSE array() (an empty array) var $var; (a variable declared, but without a value in a class)
返回值
如果 var 具有非空和非零值,则返回 FALSE。
以下内容被认为是空的:
"" (an empty string) 0 (0 as an integer) "0" (0 as a string) NULL FALSE array() (an empty array) var $var; (a variable declared, but without a value in a class)
回答by Amber
Check if...
检查是否...
if(count($array) > 0) { ... }
...if it is, then at least one key-value pair is set.
...如果是,则至少设置一个键值对。
Alternatively, check if the array is not empty():
或者,检查数组是否不为空():
if(!empty($array)) { ... }
回答by Progrock
Use array_filter if you already have keys, but want to check for non-boolean evaluated values.
如果您已经有键,但想要检查非布尔值,请使用 array_filter。
<?php
$errors = ['foo' => '', 'bar' => null];
var_dump(array_filter($errors));
$errors = ['foo' => 'Oops', 'bar' => null];
var_dump(array_filter($errors));
Output:
输出:
array (size=0)
empty
array (size=1)
'foo' => string 'Oops' (length=4)
Use:
用:
<?php
if(array_filter($errors)) {
// Has errors
}
回答by Progrock
I should add an obvious answer here. If you initialise your error array as an empty array. And later want to check if it is no longer an empty array:
我应该在这里添加一个明显的答案。如果您将错误数组初始化为空数组。后来想检查它是否不再是一个空数组:
<?php
$errors = [];
if($errors !== [])
{
// We have errors.
}
回答by M Sandbergen
You could check on both the minimum and maximum values of the array, in this case you can have a large array filled with keys and empty values and you don't have to iterate through every key-value pair
您可以检查数组的最小值和最大值,在这种情况下,您可以使用一个大数组填充键和空值,而不必遍历每个键值对
if(!min($array) && !max($array)) { ... }
回答by Anthony Rutledge
The language construct isset(), is for testing to see if variables and array elements are set and not NULL. Using is_array()would tell you if the argument you supply to it is an array. Thus, I do not think using isset() or is_array() would give you the correctand desiredresult that you are seeking.
语言结构isset()用于测试变量和数组元素是否已设置而不是 NULL。使用is_array()会告诉你你提供给它的参数是否是一个数组。因此,我不认为使用 isset() 或 is_array() 会给你你正在寻找的正确和想要的结果。
The code:
编码:
$signup_errors = array();
means that ...
意思是 ...
is_array($signup_errors);
would return true. However, this does not mean that the Boolean language rules of PHP would evaluate....
会返回true。然而,这并不意味着 PHP 的布尔语言规则会评估......
if($signup_errors)
{
//*Do something if $signup_errors evaluates to true*;
}
as true, unless some elements are added to it. When you did this,
为true,除非添加了一些元素。当你这样做时,
$signup_errors['captcha'] = 'Please Enter the Correct Security Code';
you fulfilled the PHP language requirement for the array above to evaluate to true. Now, if for some reason you wanted, or needed, to use isset() on the array elements in the future, you could. But, the conditional statement above is enough for you this case.
您满足了上述数组的 PHP 语言要求,以评估为true。现在,如果出于某种原因您希望或需要将来在数组元素上使用 isset(),您可以。但是,在这种情况下,上面的条件语句就足够了。

