本文章来给大家介绍关于php 字符串和数字比较一些问题,因为数字与字符在php中是不同的数据类型,所以在比较时可能会有很多的问题。
今天遇到一个问题,调用对方接口,按照接口说明,返回为数字0,1,2等等,其中0标示成功,其他表示不同的错误代码。程序通过 if ($ret == 0) 进行判断,开始程序是好的,今天出现问题了,由于对方接口修改,直接返回字母字符串作为错误信息提示,然后我这边就悲剧了,上述判断永远都为TRUE。
原因在于php是弱类型语言,所以可以对两个不同类型的变量进行比较操作,但最终进行比较前,php会把某一方转换称另一方一样的类型,这点很重要。如果是字符串和数字进行比较,那么php会把字符串强制转换称数字,对于纯字母的字符串,那么转换后就是0了,所以if ($ret == 0) 成了。
PHP手册/语言参考/运算符/比较运算符 可以找到.
在PHP里当两个数字型字符串(只含数字的字符串)进行比较的时候是直接转换成数值进行比较的
如下示例:(注意$a和$b两个变量的最后一位不相等)
代码如下 | 复制代码 |
//示例1 |
运行上面的程序却发现结果为equal(非我们认为的结果)
我们把$a与$b分别加一个字母a进去
代码如下 | 复制代码 |
|
这次输出的是notEqual(正确的结果)
示例1为equal是因为PHP把两个数字型字符串转换成数字型,而这两个数字刚好相等如下示例
代码如下 | 复制代码 |
$a = 511203199106034578; |
所以我们在示例1中得到的结果是equal
避免出现这种非预期结果的情况是使用类型比较符===如下示例(如果 $a 等于 $b,并且它们的类型也相同)
代码如下 | 复制代码 |
//示例4 |
这样我们就可以得到预期中的notEqual了

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment