Comparing strings, containing space with == in PHP

与世无争的帅哥 提交于 2021-02-06 11:54:31

问题


I am curious why this is happening in PHP:

'78' == ' 78' // true
'78' == '78 ' // false

I know that it's much better to use strcmp or the least ===. I also know that when you compare numerical strings with == they are casted to numbers if possible. I also can accept that the leading space is ignored, so (int)' 78' is 78, and the answer is true in the first case, but I'm really confused why it's false in the second.

I thought that '78' is casted to 78 and '78 ' is casted to 78, too, so they are the same and the answer is true, but obviously, that's not the case.

Any help will be appreciated! Thank you very much in advance! :)


回答1:


It all seems to go back to this is_numeric_string_ex C function.

To start at the implementation of ==:

ZEND_API int ZEND_FASTCALL compare_function(zval *result, zval *op1, zval *op2) {
    ...
    switch (TYPE_PAIR(Z_TYPE_P(op1), Z_TYPE_P(op2))) {
        ...
        case TYPE_PAIR(IS_STRING, IS_STRING):
            ...
            ZVAL_LONG(result, zendi_smart_strcmp(op1, op2));

If both operands are a string, it ends up calling zendi_smart_strcmp...

ZEND_API zend_long ZEND_FASTCALL zendi_smart_strcmp(zval *s1, zval *s2) {
    ...
    if ((ret1 = is_numeric_string_ex(Z_STRVAL_P(s1), Z_STRLEN_P(s1), &lval1, &dval1, 0, &oflow1)) &&
        (ret2 = is_numeric_string_ex(Z_STRVAL_P(s2), Z_STRLEN_P(s2), &lval2, &dval2, 0, &oflow2))) ...

Which calls is_numeric_string_ex...

/* Skip any whitespace
 * This is much faster than the isspace() function */
while (*str == ' ' || *str == '\t' || *str == '\n' || *str == '\r' || *str == '\v' || *str == '\f') {
    str++;
    length--;
}
ptr = str;

Which has explicit code to skip whitespace at the beginning, but not at the end.




回答2:


The space on the end of '78 ' causes PHP to treat the variable as a string. you can use trim() to strip the spaces.



来源:https://stackoverflow.com/questions/32310733/comparing-strings-containing-space-with-in-php

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