当前位置:首页 > PHP > 正文内容

php中0和字符串比较时注意的问题

高老师6年前 (2020-03-09)PHP1640

在正式介绍前先抛出一段代码:

<?php
//输入的密码
$password = empty($_POST['password']) ? 0 : $_POST['password'];

//设置的密码
$server_password = 'a123456';

if ($server_password == $password)
{
    echo '密码正确';
}
else
{
    echo '密码错误';
}

我本来的想法是用户不输入密码直接提交就当用户输入的是0,但是结果另外意外了,竟然输出密码正确。难道0还能等于a123456 ?那我们验证下:

<?php
var_dump((0 == 'a123456'));  //输出true

经过一番了解后才知道在php中如果字符串和数字进行对比,字符串将会被强制转换为int类型和数字对比,例如上面的代码等同于下面的代码:

0 == intval('a123456')

因为a123456无法转换为int型因此变为了0,如果字符串是'123456'那就不影响了,intval后依然是123456

扫描二维码推送至手机访问。

版权声明:本文由高久峰个人博客发布,如需转载请注明出处。

本文链接:https://blog.20230611.cn/post/128.html

分享给朋友:

“php中0和字符串比较时注意的问题” 的相关文章

PHP中$this和self的区别

PHP中$this和self的区别

<?php //对比$this和self   /*  * $this更倾向于对象本身  *   */   class  Par{     public   ...

PHP Startup: Unable to load dynamic library 'C:\php\ext\php_curl.dll找不到指定的模块

PHP Startup: Unable to load dynamic library 'C:\php\ext\php_curl.dll找不到指定的模块

最近在编写windows php多线程的东西,从官网下载了PHP的线程安全版,尝试开启curl扩展extension=php_curl.dllphp -m 却提示 PHP Startup: Unable to load dynamic library 'C:\php\ext\php_curl...

php mcrypt扩展被废弃的解决方案

php mcrypt扩展被废弃的解决方案

使用openssl扩展对应替换mcrypt的函数,(比较麻烦,但是openssl是未来趋势)在新版php中编译mcrypt扩展使用一个纯php代码实现的mcrypt扩展库,git地址为https://github.com/phpseclib/mcrypt_compat,每个mcrypt的方法都已经实...

php elasticsearch基础使用

php elasticsearch基础使用

elasticsearch的操作都是基于http协议的,已经有现成的php类库,composer安装即可。{     "require": {        &...

php迭代器返回值,php yield getReturn

php迭代器返回值,php yield getReturn

php生成器的方法getReturn获取生成器迭代完成后的返回值,当生成器迭代完成会将生成器的返回值返回,因此如果迭代器未进行迭代是获取不到值的,如果你没有return值则返回null,参考代码:<?php function G1() {    &nbs...

php curl Received HTTP code 403 from proxy after CONNECT

php curl Received HTTP code 403 from proxy after CONNECT

在调用微信code换openid的接口curl报错curl Received HTTP code 403 from proxy after CONNECT,错误码56。可以看到是curl的代理有问题。然后我自己电脑设置代理去访问curl请求的地址,的确也返回了403,说明代理不允许访问这个地址,联系...