简体   繁体   中英

PHP loop X amount of times

I have a string called $columns which dynamically gets a value from 1 to 7. I want to create a loop of <td></td> for however many times the value of $columns is. Any idea how I can do this?

for ($k = 0 ; $k < $columns; $k++){ echo '<td></td>'; }

Here's a more readable way to achieve this:

foreach(range(1,$columns) as $index) {
   //do your magic here
}

If you just need to use number of repeat count:

for ($i = 0; $i < 5; $i++){
    // code to repeat here
}

If $columns is a string you can cast to int and use a simple for loop

for ($i=1; $i<(int)$columns; $i++) {
   echo '<td></td>';
}

I like this way:

while( $i++ < $columns ) echo $i;

Just bear in mind if $columns is 5, this will run 5 times (not 4).

Edit: There seems to be some confusion around the initial state of $i here. You are welcome to initialise $i=0 beforehand if you wish. This is not required however as PHP is a very helpful engine and will do it for you automatically (tho, it will throw a notice if you happen to have those enabled).

A for loop will work:

for ($i = 0; $i < $columns; $i++) {
    ...
}

You can run it through a for loop easily to achieve this

$myData = array('val1', 'val2', ...);

for( $i = 0; $i < intval($columns); $i++)
{
    echo "<td>" . $myData[$i] . "</td>";
}

just repeat $n times? ... if dont mind that $n goes backwards... the advantage is that you can see/config "times" at the beginning

$n = 5;
while (--$n >= 0)
{
  // do something, remember that $n goes backwards;
}

There is a str_repeat() function in PHP, which repeats a string a number of times. The solution for your problem would be: str_repeat( '<td></td>', $columns );

为什么要使用逻辑,不要浪费那些 CPU 周期!

<td colspan="<?php echo $columns; ?>"></td>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM