Using a for loop, print the numbers from 0 to 5
March 16, 2009
I’ve been training for a ZCE certification, and found myself getting quite annoyed with some of the more obvious questions. One of the questions in the beginning of the test was which of the pieces of code would output the numbers 0 to 5 using a for loop. I mean, come on! I present some of my more creative and twisted ways of completing said task.
The obvious solution
So if you’re in an exam, the answer would be
for ($i=0; $i<=5; $i++)
{
echo $i;
}
but where's the fun in that?! Below are various different ways of doing the same thing. They all work.
They're all correct. They're just not what you'd do.
Using an array
for ($i=range(0,5),$k=$j=count($i);$j>=0;$j--)
{
echo $i[$k-$j];
}
Outputting chars
for ($i=48; $i < 54; $i++)
{
echo chr($i);
}
// or even better!
for ($i=48; $i<=53; print_r(chr($i++)));
Using a string to count
for ($i=0, $s=''; $i<6; $s.=' ', $i++)
{
echo strlen($s);
}
Using bitwise operators
for ($i=1;$i<64; $i=$i<<1)
{
echo log($i,2);
}
The know it all method
for (;;)
{
echo 'the numbers 0 to 5'; break;
}
more?
What other ways can you think of to output the numbers 0 to 5 using a for loop?