PHP类型变戏法,“字符串" == 0且"String"为==真 [英] PHP type juggling, "String" == 0 and "String" == true

查看:82
本文介绍了PHP类型变戏法,“字符串" == 0且"String"为==真的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个非常简单的问题.在PHP中,

I have a very simple question. In PHP,

if ('abc' == 0){
    //true
}
if ('abc' == 1){
    //false
}

我知道页面告诉我们,该页面应该像那样.但是,我觉得很奇怪.另外,

I know that this page tell us that it is supposed to be like that. But, I find it wierd. In addition,

if ('abc' == true){
    //true
}
if ('abc' == false){
    //false
}

这两次转换背后的逻辑是什么?

What is the logic behind theses two conversions?

推荐答案

转化1

进行字符串和整数比较时,首先将字符串转换为整数,然后进行比较.由于这些字符串中没有前导整数,因此它们将转换为零.

When string and integer comparisons are made, the string is converted to an integer first and then the comparison is made. Since there are no leading integers in those strings they convert to zero.

转化2

任何非空字符串值都是布尔值true.

Any non-empty string values are boolean true.

手册:

The following things are considered to be empty:

"" (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)

另请参见:类型比较

这篇关于PHP类型变戏法,“字符串" == 0且"String"为==真的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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