PHP“如果为真";在数组上测试始终返回true? [英] PHP "If true" test on array always returns true?

查看:102
本文介绍了PHP“如果为真";在数组上测试始终返回true?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个验证函数,如果验证通过,我想返回true,或者如果验证失败,则返回错误数组.但是,当我检查函数是否返回true时,即使返回的值是一个数组,它也返回true.为什么是这样?作为我的意思的另一个示例:

I have a validation function that I want to return true if the validation passes, or an array of errors if validation fails. However, when I check if the function returns true, it returns true even if the returned value is an array. Why is this? As a further example of what I mean:

$array = ['test' => 'test'];
if ($array == true)
  {
  echo 'true';
  }

并且我也尝试过使用字符串:

and I also tried the same with a string:

$string = 'string';
if ($string == true)
  {
  echo 'true';
  }

两者都呼应为真.

这是为什么?如果我们能够做到这一点,那为什么我们需要isset()函数呢?

Why is this? And if we can do this then why do we need the isset() function?

推荐答案

这是预期的行为,如手册 http://php.net/manual/en/types.comparisons.php

This is expected behavior as documented in the manual http://php.net/manual/en/types.comparisons.php

Expression             gettype()  empty()   is_null()   isset() boolean
-----------------------------------------------------------------------
$x = array();          array      TRUE      FALSE       TRUE    FALSE
$x = array('a', 'b');  array      FALSE     FALSE       TRUE    TRUE
$x = "";               string     TRUE      FALSE       TRUE    FALSE
$x = "php";            string     FALSE     FALSE       TRUE    TRUE

因此,空字符串或数组的结果为 false ,非空字符串或数组的结果为 true .

So an empty string or array will evaluate to false and non empty strings or arrays will evaluate to true.

另一方面, isset()将确定是否定义了变量,无论其实际值如何.唯一有所不同的值是 null .如果使用 isset()测试,则值为 null 的变量将返回false.

On the other hand isset() will determine if a variable is defined regardless of it's actual value. The only value being somehow different is null. A variable with value null will return false if tested with isset().

这篇关于PHP“如果为真";在数组上测试始终返回true?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆