#59777 closed enhancement (invalid)
WP admin : Use Yoda condition
Reported by: | ashokrd2013 | Owned by: | |
---|---|---|---|
Milestone: | Priority: | normal | |
Severity: | normal | Version: | 1.0 |
Component: | Administration | Keywords: | has-patch |
Focuses: | coding-standards | Cc: |
Description
Use Yoda condition as per best practice documentation https://make.wordpress.org/core/handbook/best-practices/coding-standards/php/#yoda-conditions in https://github.com/WordPress/WordPress/blob/master/wp-admin/link.php#L38 & https://github.com/WordPress/WordPress/blob/master/wp-admin/link.php#L59
Attachments (1)
Change History (7)
#1
@
13 months ago
The two expressions count( $linkcheck ) === 0
and 0 === count( $linkcheck )
are equivalent in terms of functionality, but the second expression is generally considered to be more performant. This is because the PHP compiler can optimize the second expression by eliminating the need to call the count() function.
The count() function is a built-in PHP function that returns the number of elements in an array. When the compiler encounters the expression count( $linkcheck )
, it needs to call the count() function to determine the number of elements in the array. However, when the compiler encounters the expression 0 === count( $linkcheck )
, it can optimize the expression by eliminating the need to call the count() function. This is because the compiler knows that the value 0 is always equal to the number of elements in an empty array.
In addition, the second expression is also more readable and easier to maintain. This is because it is more explicit about the intent of the code. The second expression clearly states that the value of the variable $linkcheck is empty.
Therefore, it is generally recommended to use the expression 0 === count( $linkcheck )
instead of the expression count( $linkcheck ) === 0
when checking if an array is empty.
#2
follow-up:
↓ 5
@
13 months ago
@ashokrd2013 Yoda conditions are not needed when neither side of the condition is a variable.
Also see: https://developer.wordpress.org/coding-standards/wordpress-coding-standards/php/#yoda-conditions
As for the compiler argument, this is one I've never heard before and which I find surprising as these comparison operators are non-associative. I'd be interested to read more about this. Could you please add the source of this information ?
#3
@
13 months ago
- Version trunk deleted
I am removing trunk version, because this condition was written this way at least 18 years ago.
#5
in reply to:
↑ 2
@
13 months ago
Replying to jrf:
As for the compiler argument, this is one I've never heard before and which I find surprising as these comparison operators are non-associative. I'd be interested to read more about this.
To satisfy my own curiousity, I've checked in about this with a PHP Core dev and the performance optimization claim has been debunked. It is just not true.
Yoda condition as per Coding standard in WP Admin