Difference between numeric and string value in PHP

北战南征 提交于 2019-12-13 16:03:11

问题


I am getting a difference when comparing two string which are 0 and '0' in PHP. Can I do anything to make them be compared equally in an if action?

Thanks!


回答1:


If you compare using:

if ('0' == 0) // if '0' is equal to 0

it should return true as the values are compared with the string being converted to a number. If you do:

if ('0' === 0) // if '0' is identical to 0

it will return false as they have to be of the same type too.

Note the triple '='




回答2:


You can also force their type to be the same before comparing:

if((int)'0' === (int)0) {
    // true
}
if((string)'0' === (string)0) {
    // true
}


来源:https://stackoverflow.com/questions/2804553/difference-between-numeric-and-string-value-in-php

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!