How can I get a php loop to print out:
1 1 2 2 3 3 all the way to 250 250. So basically count from 1 - 开发者_如何学Go250 but print out each number twice?
for ($i = 1; $i <= 250; $i++){
echo "$i ";
echo "$i ";
}
for($i = 1; $i <= 250; $i++)
{
echo $i, ' ', $i, ($i != 250 ? ' ' : NULL);
}
implode(' ', array_map('floor', range(1, 250.5, 0.5)));
for ($i = 1; $i <= 250; $i++) {
echo $i; // print the first time
echo $i; // print the second time
}
You can obviously print duplicated value with one echo statement and make the code one line shorter.
The approach to solve this is loop. You can use loops of 4 types in PHP while, for, do...while, foreach. Except for...each you can do it in other three ways. For each is used for arrays. I am writing all three loops.
while loop
$i = 1; // initialize a variable which can be used else where in the program
while($i<=250)
{
echo $i." ".$i;
$i++;
}
for loop
for($i = 1; $i <=250; $i++)
{
echo $i." ".$i;
}
the variable initialized in the braces of for loop can just be used with in the loop. do while loop
$i = 1;
do{
echo $i." ".$i;
}while($i<=250);
精彩评论