0

Is there any more professional or easier way to achieve a PHP for loop, that also iterates when there are only remaining elements? (In the current example: 1126)

<?php
$max = 11126;
$step = 2000;

for ($i = 0; $i < $max; null) {
    if ($max - $i > $step) {
        $i += $step;
    } else {
        $i += $max - $i;
    }

    echo($i . ", ");
}

?>

Outpts:

2000, 4000, 6000, 8000, 10000, 11126, 

...which is correct, but looks like too much of code.

0

2 Answers 2

3

Well, as the loop already has the continue decision, there is always something to output because $max is already the exit:

Example/Demo:

for ($i = 0;  ($i += $step) < $max;) {
    echo $i, ', ';
}
echo $max;

Program Output:

2000, 4000, 6000, 8000, 10000, 11126

All what follows is just some older playing around... .


To create exactly your output (with the comma at the end) you can use a different kind of loop that checks to loop after it looped:

Example/Demo:

$i = 0;
do {
   $i += $step;
   echo min($i, $max), ', ';
} while ($i < $max);

Program Output:

2000, 4000, 6000, 8000, 10000, 11126, 

Or why not a for loop with having the output in the pre-condition?

Example/Demo:

for (
   $i = 0;
   printf('%d, ', min($i += $step, $max)) 
   && ($i < $max);
);

Program Output:

2000, 4000, 6000, 8000, 10000, 11126, 
Sign up to request clarification or add additional context in comments.

1 Comment

This answer clearly lacks jquery. No wonder you got downvoted!
0

I don't know if my solution is more 'professionnal' but it gives you a different one at least ;)

$showSteps = function($max, $step) {
    $arr = array();
    for ($i = $step; $i <= $max; $i = $i + $step) {
        $arr[] = $i;
    }

    if (($max % $step) > 0) {
        $arr[] = intval($max/$step) * $step + $max % $step;
    }

    print implode(', ', $arr);    
};

$showSteps(11126, 2000);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.