1

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 - 250 but print out each number twice?

5 Answers 5

4
for ($i = 1; $i <= 250; $i++){
   echo "$i ";
   echo "$i ";
}
Sign up to request clarification or add additional context in comments.

4 Comments

Note you'll have a trailing space after the last 250 with this function.
ok my question was even dumber than the one that asked how to convert a number to its negative counterpart ...
The echos can be combined so you could have a oneliner: for ($i = 1; $i <= 250; $i++) echo "$i $i ";
Code golf time? foreach (range(1,250) as $i) echo "$i $i "; shaves 1 char!
3
for($i = 1; $i <= 250; $i++)
{
    echo $i, ' ', $i, ($i != 250 ? ' ' : NULL);
}

Comments

3
implode(' ', array_map('floor', range(1, 250.5, 0.5)));

1 Comment

This would be fun but implicit way to do it. I'd recommend one of the more obvious solutions.
1
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.

1 Comment

Note this function won't print spaces between the numbers.
1

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.