0

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.

1
  • Why would "text strings" have anything to do with this? Commented Apr 16, 2014 at 9:25

5 Answers 5

2

Try this:

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

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

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

1

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>";
}
?

Comments

1

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.

Comments

0

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>

2 Comments

This is literally for($i=1; $i<10; $i++) in expanded and generally unreadable form...
I know. The word for doesn't make sense in context, whilst while does - so I prefer to use this. Also allows me to adapt $i if required inside the loop.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.