我需要检查两个字符串(数字)是否相同。然而,如果其中一个字符串有一个前导零,那么所有的赌注都是无效的-它会说它们是相等的:
$hospitalno1 = "64583";
$hospitalno2 = "064583";
if ($hospitalno1 <> $hospitalno2){
echo "Different";
}
如何将这两个变量作为字符串而不是数字进行比较?
发布于 2017-10-06 13:29:49
只需使用:
<?php
$hospitalno1 = "64583";
$hospitalno2 = "064583";
if ($hospitalno1 !== $hospitalno2){
echo "Different";
}
else
{
echo "same" ;
}
?>
!==
将执行严格的数据类型+值检查,如果有任何不同,将发出警报。
发布于 2017-10-06 13:22:39
将它们转换为int
$hospitalno1 = "64583";
$hospitalno2 = "064583";
if ((int)$hospitalno1 != (int)$hospitalno2){
echo "Different";
}
但是要注意"this string“会变成0
,所以在转换之前添加is_int()
。
你应该使用!=
而不是<>
,尽管前者可以在PHP中工作,后者是跨语言的标准。
发布于 2017-10-06 13:27:51
如果我没理解错你的问题,你不希望字符串被篡改类型。
<> type juggles to match types before comparison,
causing your strings to be ints
!== is a comparitor that doesn't type juggle before comparison
下面是比较运算符的概要:http://php.net/manual/en/language.operators.comparison.php
https://stackoverflow.com/questions/46598692
复制相似问题