5
\$\begingroup\$

I have to display all the numbers between 200 and 600 (both numbers inclusive) that are divisible by 8:

for($i=200;$i<=600;$i++)
{
    if($i%8==0)
        echo $i.',';
}

It reaches maximum execution time.

\$\endgroup\$
34
\$\begingroup\$

echoimplode(",",range(200,600,8) );

\$\endgroup\$
5
  • 3
    \$\begingroup\$ about as elegant as it can get. bravo. \$\endgroup\$ – Adam Jun 30 '12 at 21:06
  • \$\begingroup\$ +1 Obviously the best answer. I would delete mine but I can't while it is accepted. \$\endgroup\$ – Martin York Jul 1 '12 at 23:45
  • \$\begingroup\$ If one more person upvotes your answer, I get a Populist badge, which would be awesome :D \$\endgroup\$ – Niet the Dark Absol Jul 2 '12 at 11:29
  • \$\begingroup\$ Epic win. Had no idea such a function existed in PHP. Thanks for sharing. \$\endgroup\$ – GordonM Jul 2 '12 at 13:16
  • \$\begingroup\$ Have a gold bade on me then. \$\endgroup\$ – Martin York Jul 2 '12 at 13:26
12
\$\begingroup\$
  1. Why do you test each number?

    Rather than $i++ you can use $i += 8. Then the test becomes redundant.

  2. Your output is terminated by ,

    ...584,592,500,
                  ^^^^  Extra trailing comma.
    

I would do:

printf('%d', 200);
for($i = 208; $i <= 600; $i += 8)
{
    printf(', %d', $i);
}
printf('\n');
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.