乐趣区

关于php:注意PHP中字符串与数字的比较

在日常开发过程中,== 运算符是咱们每天都会接触到的。这个运算符中其实埋了十分多的坑,明天咱们就来看下字符串和数字用 == 比拟须要留神的问题。

首先来看看这些代码:


echo '"1234" == "1234" is '. ('1234'==' 1234'), PHP_EOL;
echo '"1234" == "\n1234" is '. ('1234'=="\n1234"), PHP_EOL;
echo '"1234" == "1234" is '. ('1234'=='1234'), PHP_EOL;
echo '"1234" == "1234" is '. ('1234'=='1234 '), PHP_EOL;
echo '"1234" == "1234\n" is '. ('1234'=="1234\n"), PHP_EOL;

都是字符串的 == 操作,它们的后果会是什么呢?


"1234" == "1234" is 1
"1234" == "\n1234" is 1
"1234" == "1234" is 1
"1234" == "1234" is 
"1234" == "1234\n" is 

没错,空格或者制表符号在前的会疏忽掉这些符号,也就是说,这些字符串在比照的时候进行了类型转换,都被强转成了 int 型。而特殊字符在后的,则会依照字符串类型进行比对,那么,纯字符类型呢?


echo '"aa" == "aa" is '. ('aa'==' aa'), PHP_EOL;
echo '"aa" == "\naa" is '. ('a'=='\naa'), PHP_EOL;
echo '"aa" == "aa" is '. ('aa'=='aa'), PHP_EOL;
echo '"aa" == "aa" is '. ('aa'=='aa '), PHP_EOL;
echo '"aa" == "aa\n" is '. ('aa'=="aa\n"), PHP_EOL;

这时候的后果就合乎咱们的预期了,他们自身就是字符串的比对,不会进行任何类型的转换:


"aa" == "aa" is 
"aa" == "\naa" is 
"aa" == "aa" is 1
"aa" == "aa" is 
"aa" == "aa\n" is 

综上试验后果得悉,当字符串的内容都是 int 数据时,字符串的 == 比拟会疏忽在字符串后面呈现的空格或者制表符号将它们强制转换成 int 类型。而只有字符串中蕴含文本或者特殊符号在数字的前面,就会以文本形式进行比拟,如纯文本或者混合文本(”11aa”、”11n”、”aa11 “)。

测试代码:https://github.com/zhangyue0503/dev-blog/blob/master/php/201910/source/%E6%B3%A8%E6%84%8F%EF%BC%81PHP%E4%B8%AD%E5%AD%97%E7%AC%A6%E4%B8%B2%E4%B8%8E%E6%95%B0%E5%AD%97%E7%9A%84%E6%AF%94%E8%BE%83.php

参考链接:https://www.php.net/manual/zh/language.operators.comparison.php

各自媒体平台均可搜寻【硬核项目经理】

退出移动版