Comparing strings containing space with == in PHP

I am curious why this happens in PHP:

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

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

I thought that '78' is added to 78 , and '78 ' also added to 78 , so they are the same and the answer is correct, but obviously this is not so.

Any help would be appreciated! Thanks a lot in advance!:)

+6
source share
2 answers

Everything seems to be returning to this is_numeric_string_ex C function .

To start with 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 zendi_smart_strcmp , it calls 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 call 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; 

Whoever has explicit code for missing spaces at the beginning , but not at the end.

+7
source

The space at the end of '78 'forces PHP to treat the variable as a string. you can use trim () to separate spaces.

-1
source

All Articles