Make WordPress Core

Attachments (1)

59777.patch (711 bytes) - added by ashokrd2013 7 months ago.
Yoda condition as per Coding standard in WP Admin

Download all attachments as: .zip

Change History (7)

@ashokrd2013
7 months ago

Yoda condition as per Coding standard in WP Admin

#1 @ashokrd2013
7 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.

Last edited 7 months ago by ashokrd2013 (previous) (diff)

#2 follow-up: @jrf
7 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 @oglekler
7 months ago

  • Version trunk deleted

I am removing trunk version, because this condition was written this way at least 18 years ago.

#4 @sabernhardt
7 months ago

  • Version set to 1.0

added 20 years ago: [279] :)

#5 in reply to: ↑ 2 @jrf
7 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.

#6 @johnbillion
7 months ago

  • Milestone Awaiting Review deleted
  • Resolution set to invalid
  • Status changed from new to closed
Note: See TracTickets for help on using tickets.