Bad code construct throughout the entire codebase

  • Christopher Ambler
  • Topic Author
  • Offline
  • New Member
  • New Member
More
3 years 2 weeks ago - 3 years 2 weeks ago #142813 by Christopher Ambler
Bad code construct throughout the entire codebase was created by Christopher Ambler
Throughout the codebase, the following construct is used:

for ($i = 0; $n = count($rows), $i < $n; $i++)

This is incorrect, as the conditional, in PHP, may not execute the second statement if the first statement evaluates to false, but still executes count() every single time. This causes two issues. First, a warning is generated because of the short-circuit evaluation, even if it would never happen. Second, the overhead of the repeated count() calls is huge.

Could you please modernize your code as thus?

for ($i = 0, $n = count($rows); $i < $n; $i++)

You only need to set $n once this way and you avoid short-circuit warnings.
Last edit: 3 years 2 weeks ago by Christopher Ambler.

Please Log in or Create an account to join the conversation.

Moderators: Giang Dinh Truong