加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

如何检查PHP数组是否具有任何值?

发布时间:2020-12-13 16:39:15 所属栏目:PHP教程 来源:网络整理
导读:我正在使用注册表单,我使用 PHP,在我的处理部分我运行一些代码,如果提交的项目失败,我然后将其添加到错误数组. 下面是一段代码,我正在找到最好的方法来确定是否应该触发错误. 所以如果在错误数组中设置了一个值,那么我需要重定向并做一些其他的东西. 我正在
我正在使用注册表单,我使用 PHP,在我的处理部分我运行一些代码,如果提交的项目失败,我然后将其添加到错误数组.

下面是一段代码,我正在找到最好的方法来确定是否应该触发错误.

所以如果在错误数组中设置了一个值,那么我需要重定向并做一些其他的东西.

我正在考虑使用isset或者is_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
}

它是如何工作的?当转换为布尔值时,空数组将转换为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(),因为它具有类似的语义.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读