Alex Rivera | Logout

PHP Increment by Half

Asked 2011-01-27T22:21:39.130
9

I have a quick question, which is probably easy to answer. I've goolged around, but not sure if I am searching correctly or what. Anyway, using PHP, how can I increment by halves?

For example, I know I can use the following loop:

<?php 
for ($i=1; $i<21; $i++) {
    print($i);
}

And it will print 1 - 20.

But, how can I get it to output something like the following:

1
1.5
2
2.5
etc...

Sorry for my ignorance on this, I'm just not sure how to go about it. Thanks!

Edit
Report

2 Answers

31

Change $i++ to $i += 0.5. Also, to print each number on its own line you need to use \n (or <br> if you're outputting HTML to a browser).

for ($i = 1; $i < 21; $i += 0.5) {
    print($i . "\n");
}

The above code will print 20.5 because it's less than 21. If you want to print a maximum of 20, change the loop condition to check $i <= 20 instead:

for ($i = 1; $i <= 20; $i += 0.5) {
    print($i . "\n");
}
answered 2011-01-27T22:23:03.357
2

instead of $i++, use $i += .5

answered 2011-01-27T22:23:06.127

Your Answer