简体   繁体   中英

Comparing strings, containing space with == in PHP

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! :)

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM