doulezhi5326 2015-06-25 12:57
浏览 5
已采纳

Intval的意外行为[重复]

This question already has an answer here:

Here, $username is a userinput, and I am trying to check if the entry was a username, or a userid (all integers)

I thought to use the intval function to see if $username and intval($username) is same, which means the input is a userid.

The input I gave was google. and intval('google') is 0. Why does the true part of the if statement get executed? Any idea?

I amnt using === because the userinput will be a string.

if($username == intval($username))
    {
     echo "userid";
    }
    else
    {
    echo "username";
    }

Not sure why the unexpected behaviour is happening.

</div>
  • 写回答

2条回答 默认 最新

  • duange051858 2015-06-25 13:03
    关注

    It is happening because of the conversion & type juggling of comparison operators.

    intval('anystring') will be 0.

    And when a string is getting compared it is also converted into numeric value. So when the string is converted it will also be 0.

    If you compare a number with a string or the comparison involves numerical strings, then each string is converted to a number and the comparison performed numerically. These rules also apply to the switch statement. The type conversion does not take place when the comparison is === or !== as this involves comparing the type as well as the value.

    So in this case 'google1' == intval('google') will be 0 == 0 and that is true. For this type of comparison always use identical(===) comparison.

    comparison

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法