Akala Volo
Akala Volo

Reputation: 13

Are empty for loops in PHP considered bad practice?

I'm currently writing a bit of code to shift the values of an associative array to the right in PHP 7.0, and have used a for loop with no instructions in it:

$array = array("one" => 1, "two" => 2, "three" => 3, "four" => 4);
$first = reset($array);
$last = end($array);

for (end($array); current($array) !== $first && key($array) !== null; $array[key($array)] = prev($array)){
    continue;
}
$array[key($array)] = $last;

The code works and outputs what I need, but I can't help but feel like there's something wrong with such a structure. Maybe there's a clearer way of doing it? (I'm asking myself this primarily because my code will not be maintained by me in the future, and I want it to be as clean as possible)

I couldn't find anything on the subject on the manual page or on blogs. Is it generally frowned upon or more up to one's own opinion?

Upvotes: 1

Views: 130

Answers (2)

Don't Panic
Don't Panic

Reputation: 41810

Just a suggestion for a different approach that may be a little easier to read than a loop.

// save the keys
$keys = array_keys($array);
// shift the values right
array_unshift($array, array_pop($array));
// restore the keys
$array = array_combine($keys, $array);

As far as your concern for whoever will be maintaining the project in the future, whether it's you or someone else, you should try to write the code in such a way that it is obvious what each part is supposed to do. One easy way to do that:

function shift_values_right(array $array) {  // code that does that }

I'd prefer this over an explanatory comment if I inherited the project.

Upvotes: 0

Leo Aso
Leo Aso

Reputation: 12463

I'll say its bad practice, because even though it's valid, I find from experience that refactoring it into a while loop almost always makes it more readable.

$array = array("one" => 1, "two" => 2, "three" => 3, "four" => 4);
$first = reset($array);
$last = end($array);

while (current($array) !== $first && key($array) !== null) {
    $array[key($array)] = prev($array);
}

$array[key($array)] = $last;

Upvotes: 7

Related Questions