Write a FOR loop in PHP that prints the numbers 0-9 to the page

How would i go about this?

homework assignment?

what have you tried so far?

Not really. Saw this question on a skills test. I have no idea where to start.
I first inclination is to put the numerals 1-9 in array and wrote a for loop to simply print all of the array contents?

That would be too easy. There’s gotta be a way to handle numbers programmatically. Can you point me in the right direction?

http://us2.php.net/manual/en/control-structures.for.php


foreach(range(0,9) as $num) {
  echo $num;
}

http://us3.php.net/manual/en/function.range.php

In a for loop as requested:-


<?php
for( $iCounter = 0 ; $iCounter <= 9 ; $iCounter++ )
{
    echo $iCounter . '<br />';
}
?>

Would have been good to let him have a stab at it first, noone learns from copying and pasting!

Possibly, but as a solution had already been posted I thought it best he at least gets what he asked for.

Saying that, I usually find it easier to learn something given an example, it’s all good and well trying to cobble a solution together, but if you don’t even know where to start…

It’s nearly Christmas too, festive giving and all that! :slight_smile:

Nah, normally I would let people have a stab at it first, post something up, then help them with that. Better than just giving away the answer straight off :slight_smile:

But yeh, since an answer had already been posted, may as well post the one he wanted!

If it doesn’t have to specifically be a for-loop, you could do:


echo implode(",", range(0,9));

or even

echo '1 2 3 4 5 6 7 8 9';

OK, if we really want to get down and dirty…


for($i=0; $i<=1; $i++) {
    echo 'the numbers 0-9';
}

should answer the question exactly…

Ah, why not confuse things further then :stuck_out_tongue:

for ($i=0;$i<=9;print $i++);
for($i=48;$i<=57;print(chr($i++)));

Have a version in brainf*ck as well:

<++++++++[>++++++<-]>>++++++++++[<.+>-]

$x = 0;

while ($x < 10)
{
	echo $x++;
}

$x = 10;
while ($x) echo 10 - ($x--);
for ($d1=0;$d1<2;$d1++)
 for ($d2=0;$d2<2;$d2++)
  for ($d3=0;$d3<2;$d3++)
   for ($d4=0;$d4<2;$d4++) {
       echo base_convert($d1.$d2.$d3.$d4,2,10);
    if ($d1.$d2.$d3.$d4 == "1001") break 4;
   }//for

LMAO, If bruin03 doesn’t get an A* then its a fix!

Now I’m spending all my time trying to make obscure solutions to this problem…

wow, good show StormRider.

Another…


<?php
$aRange = array('M','N','O','A','Q','g','w');
for ($i=0;$i<=6;$i++)
{
    for ($j=0;$j<=6;$j++)
    {
        $k = base64_decode($aRange[$i].$aRange[$j].'==');
        if(is_numeric($k))
        {
            echo ($l != $k) ? $k . '<br />' : null ;
            $l = $k;
        }
    }
}
?>

<?php
for($i=0; $i<=9; $i++)
{
echo $i;
}
?>