[英]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.我有一个名为$columns
的字符串,它动态地获取一个从 1 到 7 的值。我想创建一个<td></td>
循环,无论$columns
的值是多少次。 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如果$columns
是一个string
你可以转换为int
并使用一个简单的 for 循环
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).请记住,如果$columns
是 5,这将运行 5 次(不是 4 次)。
Edit: There seems to be some confusion around the initial state of $i
here.编辑:这里$i
的初始状态似乎有些混乱。 You are welcome to initialise $i=0
beforehand if you wish.如果您愿意,欢迎您事先初始化$i=0
。 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).然而,这不是必需的,因为 PHP 是一个非常有用的引擎,并且会自动为您完成(不过,如果您碰巧启用了这些引擎,它会发出通知)。
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>";
}
just repeat $n times?只是重复$n次? ... if dont mind that $n goes backwards... the advantage is that you can see/config "times" at the beginning ...如果不介意 $n 倒退...优点是您可以在开头看到/配置“时间”
$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. PHP 中有一个str_repeat()
函数,它可以多次重复一个字符串。 The solution for your problem would be: str_repeat( '<td></td>', $columns );
您的问题的解决方案是: str_repeat( '<td></td>', $columns );
为什么要使用逻辑,不要浪费那些 CPU 周期!
<td colspan="<?php echo $columns; ?>"></td>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.