Tuesday 26 July 2016

php - What is the difference between and !=




In PHP to check non-equality (without checking type) you can do this:




if( A != B ) {
DO SOMETHING;
}


But you can also do this, which has the same result:



if( A <> B ) {
DO SOMETHING;
}



Is there any difference?



Does using != over <> change the evaluation in any way, shape, or form?


Answer



Forgetting documentation for a minute, let's check out the source code. Let's start with the scanner (lexer):



"!="|"<>" {
return T_IS_NOT_EQUAL;

}


So they parse to the same token. Let's check out the parser:



expr T_IS_NOT_EQUAL expr { zend_do_binary_op(ZEND_IS_NOT_EQUAL, &$$, &$1, &$3 TSRMLS_CC); }


So we know that the opcode that's fired is ZEND_IS_NOT_EQUAL...




Now, let's check out the operation:



static int ZEND_FASTCALL  ZEND_IS_NOT_EQUAL_SPEC_CONST_CONST_HANDLER(ZEND_OPCODE_HANDLER_ARGS)
{
USE_OPLINE

zval *result = &EX_T(opline->result.var).tmp_var;

SAVE_OPLINE();
ZVAL_BOOL(result, fast_not_equal_function(result,

opline->op1.zv,
opline->op2.zv TSRMLS_CC));

CHECK_EXCEPTION();
ZEND_VM_NEXT_OPCODE();
}


So there's literally no difference. Since they parse to the same token, they have exactly the same precedence (so the docs are either wrong or misleading). Since they use the same executor, and there's no decision point in the opcode routine, they execute identical code.




So yes, <> and != are 100% interchangeable, and there's absolutely no technical reason to use one over the other.



With that said, there is something significant to gain by being consistent. So I'd recommend just sticking with != and being done with it...



Edit



I've updated the docs to reflect this, and fixed another issue with the precedence order (++ and -- have the same precedence as casting). Check it out on docs.php.net


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...