PHP Increment by Half
I have a quick question, which is probably easy to answer. I've goolged around, but not s开发者_开发技巧ure 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!
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");
}
Just one more solution to choose from.
foreach (range(1, 20, 0.5) as $i) {
// Do something with $i
}
instead of $i++
, use $i += .5
Loop to double the amount (adjust upper and lower bounds appropriately) and divide by two in the output.
E.g.
for ($i=2; $i<41; $i++) print($i/2);
to output from 1 to 20 in increments of .5
Here's something that could work.
$i += round(exp(log(2)/2) * 2) / 2 - ENT_QUOTES + IMAGETYPE_JPEG;
精彩评论