tags:

views:

75

answers:

4

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?

+3  A: 
for ($i = 1; $i <= 250; $i++){
   echo "$i ";
   echo "$i ";
}
Mark Moline
Note you'll have a trailing space after the last 250 with this function.
Stephen Melrose
ok my question was even dumber than the one that asked how to convert a number to its negative counterpart ...
stef
The `echo`s can be combined so you could have a oneliner:`for ($i = 1; $i <= 250; $i++) echo "$i $i ";`
Benedict Cohen
Code golf time? `foreach (range(1,250) as $i) echo "$i $i ";` shaves 1 char!
meagar
+1  A: 
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.

RaYell
Note this function won't print spaces between the numbers.
Stephen Melrose
+3  A: 
for($i = 1; $i <= 250; $i++)
{
    echo $i, ' ', $i, ($i != 250 ? ' ' : NULL);
}
Stephen Melrose
+3  A: 
implode(' ', array_map('floor', range(1, 250.5, 0.5)));
soulmerge
That's a slick way to do it
chris
This would be fun but implicit way to do it. I'd recommend one of the more obvious solutions.
erisco