php - Intval 的意外行为

标签 php

在这里,$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/

相关文章:

php - Laravel Blade 模板@extends

php - 使用 CodeIgniter 的简单登录系统在登录时返回 404

php 脚本无法使用 SSL 连接到 MySQL

php - mysqli - fatal error

php - 网站框架

php - 有条件地从 <head> 添加 remove &lt;script&gt;, <link> 节点

javascript - 使用 JQuery 获取输入类型文件中的文件并 move 它

php - Codeigniter Controller 返回上一页

php artisan migrate - 错误 - Illuminate\Database\QueryException : SQLSTATE[HY000] [2054]

即使没有给出关键字,php mysql 查询也会获取数组