# 转换与不同的比较

If I have a variable which is given a string that could also be a number, as so:

``````\$a = "1";
``````

If I want to check if it is indeed equal to 1, is there any functional difference between

``````if((int)\$a == 1) {
whatever();
}
``````

and

``````if(\$a == "1") {
whatever();
}
``````

• 点赞
• 写回答
• 关注问题
• 收藏
• 复制链接分享
• 邀请回答

#### 3条回答

• ``````\$a = "1"; // \$a is a string
\$a = 1; // \$a is an integer
``````

1st one

``````if((int)\$a == 1) {
//int == int
whatever();
}
``````

2nd one

``````if(\$a == "1") {
//string == string
whatever();
}
``````

But if you do

``````\$a = "1"; // \$a is a string

if(\$a == 1) {
//string & int
//here \$a will be automatically cast into int by php
whatever();
}
``````
点赞 评论 复制链接分享
• since your question also asks about other languages you might be looking for more general info, in which case dont forget about triple equals. which is really really equal to something.

``````\$a = "1";
if (\$a===1) {
// never gonna happen
}
\$b = 1;
if (\$b === 1) {
// yep you're a number and you're equal to 1
}
``````
点赞 评论 复制链接分享
• In the first case you need to convert and then compare while in the second you only compare values. In that sense the second solutions seems better as it avoids unnecessary operations. Also second version is safer as it is possible that `\$a` can not be casted to int.

点赞 评论 复制链接分享