Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/variables/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/arduino/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 转换与不同比较_Php_Variables_Comparison - Fatal编程技术网

Php 转换与不同比较

Php 转换与不同比较,php,variables,comparison,Php,Variables,Comparison,如果我有一个变量,它被赋予一个字符串,也可以是一个数字,那么: $a = "1"; 如果我想检查它是否真的等于1,两者之间有函数上的区别吗 if((int)$a == 1) { whatever(); } 及 这里我考虑的是PHP,但欢迎您回答其他语言。在第一种情况下,您需要转换然后进行比较,而在第二种情况下,您只需要比较值。从这个意义上讲,第二种解决方案似乎更好,因为它避免了不必要的操作。第二个版本更安全,因为$a可能无法强制转换为int $a = "1"; // $a is a

如果我有一个变量,它被赋予一个字符串,也可以是一个数字,那么:

$a = "1";
如果我想检查它是否真的等于1,两者之间有函数上的区别吗

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


这里我考虑的是PHP,但欢迎您回答其他语言。

在第一种情况下,您需要转换然后进行比较,而在第二种情况下,您只需要比较值。从这个意义上讲,第二种解决方案似乎更好,因为它避免了不必要的操作。第二个版本更安全,因为
$a
可能无法强制转换为int

$a = "1"; // $a is a string
$a = 1; // $a is an integer
第一个

if((int)$a == 1) {
 //int == int
    whatever();
}
第二个

if($a == "1") {
   //string == string
    whatever();
}
但如果你这样做了

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

if($a == 1) {
   //string & int
   //here $a will be automatically cast into int by php
    whatever();
}

因为你的问题也询问其他语言,你可能在寻找更一般的信息,在这种情况下,不要忘记三重相等。这真的等于什么

$a = "1";
if ($a===1) {
  // never gonna happen
}
$b = 1;
if ($b === 1) {
  // yep you're a number and you're equal to 1
}

比较字符串不是比比较数字更难吗?如果它是一个较长的数字,比如
$a=“34287”
,那么转换为整数将再次涉及对字符串的迭代加上一些额外的操作。不,在PHP中没有功能上的区别。第一种情况是PHP在第二种情况下的幕后工作。这取决于
$a
来自何处。如果用户输入,请小心,好像第一个为真,第二个为假。
$a = "1";
if ($a===1) {
  // never gonna happen
}
$b = 1;
if ($b === 1) {
  // yep you're a number and you're equal to 1
}