Make WordPress Core

Opened 6 years ago

Last modified 5 years ago

#45825 new enhancement

Use of same loop variable in inner foreach loop can be error-prone

Reported by: subrataemfluence's profile subrataemfluence Owned by:
Milestone: Future Release Priority: low
Severity: trivial Version: 5.0.2
Component: Upgrade/Install Keywords: has-patch
Focuses: coding-standards Cc:

Description

It is not a good practice and not recommended to use the same loop variable in both outer and inner loop. In wp-admin/install-helper.php function maybe_drop_column does the following:

function maybe_drop_column( $table_name, $column_name, $drop_ddl ) {
   ...
   foreach( ...  as $column ) {
     ...
     foreach( ... as $columns ) {
       ...
     }
   }
}

I would recommend to change the inner loop variable to $recheck_column.

Attachments (1)

45825.diff (598 bytes) - added by subrataemfluence 6 years ago.

Download all attachments as: .zip

Change History (4)

#1 @swissspidy
6 years ago

  • Keywords dev-feedback removed
  • Milestone changed from Awaiting Review to Future Release
  • Priority changed from normal to low
  • Severity changed from normal to trivial

#2 in reply to: ↑ description @madivad
5 years ago

Replying to subrataemfluence:
You could edit the ticket to remove a typo (the second reference to $column has $columns, hence the only reason why I delved into the code to actually check what was there. $columns would mean that it is a new variable and hence not required to be changed.

However, the typo is in your original post and they are in fact the same variable name.

I do submit it is irrelevant and given the nature of scoping within PHP, the inner reference to $column cannot alter or modify the outer loop variable as it is not passed by reference (the inner would need to be &$column). Given this (that the inner foreach variable can never alter the outer loop) it's a non-issue and the code could stand as-is, however, for clarity there is no reason this should not be committed.

It is not a good practice and not recommended to use the same loop variable in both outer and inner loop. In wp-admin/install-helper.php function maybe_drop_column does the following:

function maybe_drop_column( $table_name, $column_name, $drop_ddl ) {
   ...
   foreach( ...  as $column ) {
     ...
     foreach( ... as $columns ) {
       ...
     }
   }
}

I would recommend to change the inner loop variable to $recheck_column.

#3 @subrataemfluence
5 years ago

  • Type changed from defect (bug) to enhancement

@madivad Thank you for your reply. I am sorry for the typo! I should have been more careful about it. What you said absolutely right, i.e. inner loop variable cannot alter the value of outer loop. I created this ticket only for clarity as you have correctly pointed out.

Regarding editing the actual post, I have no option to do it?!

Note: See TracTickets for help on using tickets.