View Full Version : Beginner needs help with loop

10-22-2012, 04:47 PM
Hey. So I just started doing php and I encountered a little problem. When i run this

for ($i=3; $i<=600; $i+=3)
echo $i.",";

It works, but some of the texts gets "hidden" because the text will just continue on without any column shift. But how do I implement a column shift, say every 10th number?

10-22-2012, 05:04 PM
I'm guessing that by column shift you mean new line.

You can add a small if statement that tests whether a number is divisible by 10.

So it becomes:

for ($i=3; $i<=600; $i+=3) {
if($i%10 == 0){
echo $i."<br />";
echo $i.",";

10-22-2012, 05:06 PM
What is a "column shift"?
The loop itself is fine, although with any control branch I'd recommend using { and } regardless of how many lines it has. It looks silly combining multiples:

if (false)
print 'never gets here';
print 'Got here.';
define('GOTSHERE', 'here I am');

10-22-2012, 05:38 PM
Thanks for the help :D
And yes, column shift was new line :P

10-23-2012, 10:30 AM
Bored at work...

$b = !((bool)$i % 10) ? "<br>" : ",";
echo ($i . $b);

I challenge you all to come up with a more convoluted way of doing this.

10-23-2012, 10:41 AM
Heres another more retarded version, utilizing some amazing typecasting functions from php:

$tmp = (string)$i;
$b = !($tmp{strlen($tmp) -1}) ? "<br>" : ",";
echo($i . $b);