...

View Full Version : Beginner needs help with loop



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


<?php
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?

Redcoder
10-22-2012, 04: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:



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

Fou-Lu
10-22-2012, 04: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';
else
{
print 'Got here.';
define('GOTSHERE', 'here I am');
}

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

idalatob
10-23-2012, 09: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.

idalatob
10-23-2012, 09: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);



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum