php - 如何检查 PHP 数组是否设置了任何值?

标签 php arrays

我正在处理一个注册表单,我正在使用 PHP,在我的处理部分我运行一些代码,如果提交的项目失败,我然后将它添加到错误数组中。

下面是代码片段,我现在需要找到最佳方法来确定是否应该触发错误。

因此,如果在错误数组中设置了一个值,那么我需要重定向并做一些其他事情。

我正在考虑使用 issetis_array 但我不认为这是答案,因为我使用 **$signup_errors = array()** 这不会使 is_array 为真吗?

有谁能推荐一个好的方法吗?

//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';

最佳答案

if ($signup_errors) {
  // there was an error
} else {
  // there wasn't
}

它是如何工作的?转换为 bool 值时,空数组将转换为 false。每个其他数组都转换为 true。来自PHP manual :

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).

你也可以使用 empty()因为它具有相似的语义。

关于php - 如何检查 PHP 数组是否设置了任何值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1371198/

相关文章:

php - 从php数组中删除行

php - 如何在通知中心向特定用户发送推送通知?

arrays - 部分选择多维 systemverilog 数组作为 1D 向量

arrays - 使用流水线将字符串拆分为多维数组

php - jQuery 函数在 IE 中被触发两次...?

javascript - opencart $_GET 使用参数重定向到 index.php

php - 如何创建表并在其中插入数据,但如果已有同名表,则只需插入数据并且不再创建表

java - 使用数组列表将标记添加到 Google map 。安卓

ios - 如何在没有 afnetworking 的情况下使用 get 请求将数组作为参数发送到 url

java - ArrayList 未填充