【问题标题】:PHP For looping a string multiple times in a listPHP用于在列表中多次循环字符串
【发布时间】:2014-04-16 09:23:55
【问题描述】:

所以基本上我需要使用 for 循环在列表中打印十次“Hi mate”。我该怎么做呢?我知道如何 for 循环编号,但我不知道它如何处理文本字符串。

<!DOCTYPE html>
<html>
    <head>
        <title></title>
    </head>
    <body>
        <ul>
           <?php
              for (???){
                 echo "<li>$string</li>";
              }
           ?>
        </ul>
    </body>
</html>

有什么建议吗?这是我第一次使用 PHP,所以很好。

【问题讨论】:

  • 为什么“文本字符串”与此有关?

标签: php list for-loop


【解决方案1】:

试试这个:

echo str_repeat("<li>$string</li>",10);

如果for 循环让您感到害怕,请删除它;)

【讨论】:

    【解决方案2】:

    试试看:

    for ($i = 0; $i < 10; $i++) {
        echo "<li>$string</li>";
    }
    

    你也应该考虑阅读http://www.php.net/manual/en/language.control-structures.php

    【讨论】:

      【解决方案3】:

      将“for”与 2 var 一起使用,首先是 $i 用于循环,其次是 $count 用于停止循环。

      <?php
      for ($i = 0; $i<$count; $i++){
         echo "<li>$string</li>";
      }
      ?
      

      【讨论】:

        【解决方案4】:

        试试这个,

        <!DOCTYPE html>
        <html>
        <head>
            <title></title>
        </head>
        <body>
            <ul>
               <?php
                  for ($i=0;$i<10;$i++){
                     echo "<li>Hi Mate</li>";
                  }
               ?>
            </ul>
        </body>
        </html>
        

        您可以添加 css 来消除这些点。

        【讨论】:

          【解决方案5】:

          不是实现这一目标的最短方法,而是我如何做到这一点,因为这对我来说是合乎逻辑的。

          如下。

          <!DOCTYPE html>
          <html>
              <head>
                  <title></title>
              </head>
              <body>
                  <ul>
                     <?php
                        $string = 'Hi mate'; //String ready to print.
                        $i=1; // Sets value of $i to begin count.
                        while($i < 10): // Checks $i is still less than 10.
                           echo "<li>$string</li>";
                           $i++; //Add 1 to $i to up the count.
                        endwhile;
                     ?>
                  </ul>
              </body>
          </html>
          

          【讨论】:

          • 这实际上是 for($i=1; $i&lt;10; $i++) 的扩展格式,通常不可读...
          • 我知道。 for 这个词在上下文中没有意义,而while 有——所以我更喜欢使用它。如果需要,还允许我在循环内调整$i
          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2021-04-18
          • 2015-09-15
          • 1970-01-01
          • 1970-01-01
          • 2021-10-11
          • 2015-12-11
          • 2014-09-19
          相关资源
          最近更新 更多