转换与不同的比较

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();
}

Here I am thinking about PHP, but answers about other languages will be welcome.

$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();
}

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.

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
}