dongluo6343 2017-10-06 05:16
浏览 49

比较字符串与前导零

I need to check if two strings (numbers) are the same. However if one of the strings has a leading zero, then all bets are off - it says they are equal:

$hospitalno1 = "64583";                 
$hospitalno2 = "064583";

if ($hospitalno1 <> $hospitalno2){ 
    echo "Different";
} 

How can I compare these two variables as strings rather than as numbers?

  • 写回答

6条回答 默认 最新

  • douchou8935 2017-10-06 05:22
    关注

    Cast them to int:

    $hospitalno1 = "64583";                 
    $hospitalno2 = "064583";
    
    if ((int)$hospitalno1 != (int)$hospitalno2){ 
        echo "Different";
    } 
    

    yet beware "this string" will become 0, so add is_int() prior conversion.

    Also instead of <> you should use != despite the fact the former will work in PHP, the latter is cross language standard.

    评论

报告相同问题?