PHP 循环 X 次

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14672062/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 07:45:45  来源:igfitidea点击:

PHP loop X amount of times

phploops

提问by Ahmed

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

我有一个名为的字符串$columns,它动态地获取一个从 1 到 7 的值。我想创建一个<td></td>for的循环,无论值$columns是多少次。知道我该怎么做吗?

回答by Fatih Donmez

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

回答by murze

Here's a more readable way to achieve this:

这是实现此目的的更具可读性的方法:

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

回答by Pankrates

If $columnsis a stringyou can cast to intand use a simple for loop

如果$columns是一个string你可以投射到int并使用一个简单的 for 循环

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

回答by Blender

A forloopwill work:

一个for循环将工作:

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

回答by cronoklee

I like this way:

我喜欢这种方式:

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

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

请记住,如果$columns是 5,这将运行 5 次(不是 4)

回答by David Barker

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

您可以轻松地通过 for 循环运行它来实现此目的

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

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