gpt4 book ai didi

php - Intval 的意外行为

转载 作者:行者123 更新时间:2023-12-02 09:32:46 28 4
gpt4 key购买 nike

在这里,$username是一个用户输入,我正在尝试检查该条目是否是用户名或用户 ID(所有整数)

我想用intval函数来看看是否$usernameintval($username)是一样的,这意味着输入的是一个userid。

我给出的输入是google 。和intval('google')是0。为什么if语句的true部分会被执行?有什么想法吗?

我没有使用===因为用户输入将是一个字符串。

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

不确定为什么会发生意外行为。

最佳答案

发生这种情况是因为比较运算符的转换类型杂耍

intval('anystring') 将是 0

当比较字符串时,它也会转换为数值。因此,当字符串转换时,它也将是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.

因此,在这种情况下,'google1' == intval('google') 将是 0 == 0,这是事实。对于这种类型的比较,请始终使用相同(===)比较。

comparison

关于php - Intval 的意外行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31051067/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com