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
1
2
3
4
| 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
1
2
3
4
| for ($i=range(0,5),$k=$j=count($i);$j>=0;$j--)
{
echo $i[$k-$j];
} |
Outputting chars
1
2
3
4
5
6
7
| 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
1
2
3
4
| for ($i=0, $s=''; $i<6; $s.=' ', $i++)
{
echo strlen($s);
} |
Using bitwise operators
1
2
3
4
| for ($i=1;$i<64; $i=$i<<1)
{
echo log($i,2);
} |
The know it all method
1
2
3
4
| 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?
Tags:
for,
loops,
PHP,
zce
Both comments and trackbacks are currently closed.
Browse
Browse in PHP Server side
Related Posts
One Comment
dude … loops are so yesterday …
<?php
function counter($to=0, $cur=0) {
if ($cur