Andrew P
Andrew P

Reputation: 1597

PHP For looping a string multiple times in a list

So basically I need to use a for loop to print "Hi mate" ten times in a list. How do I do this? I know how to for loop numbers but i have no idea how it works with text strings.

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

Any suggestions? It's the first time I'm using PHP so be nice.

Upvotes: 0

Views: 422

Answers (5)

Wit Wikky
Wit Wikky

Reputation: 1542

Try this,

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

You can add css to get rid of those dots.

Upvotes: 1

gatfil
gatfil

Reputation: 45

Use "for" with 2 var, first it is $i for loop and second it is $count for stop your loop.

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

Upvotes: 1

Matt The Ninja
Matt The Ninja

Reputation: 2731

Not the shortest way to achieve this, but how i do this as it makes logical sense to me.

As below.

<!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>

Upvotes: 0

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324790

Try this:

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

If the for loop scares you, remove the need for it ;)

Upvotes: 2

hsz
hsz

Reputation: 152284

Just try with:

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

Also you should concider reading http://www.php.net/manual/en/language.control-structures.php

Upvotes: 1

Related Questions