How to pick variable and print several "<li>" according to the variable number?

Asked

Viewed 82 times

0

I have a variable $abas = 4.

I need PHP to make one echo in the variable number, in this case it would be 4.

The result should be:

<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>

I am a beginner in PHP, what is the best way to do this?

1 answer

7


For what you are wanting to do, I recommend using the for.

Example:

<?php for ($i = 1; $i <= $abas; $i++): ?>
    <li><?= $i ?></li>
<?php endfor ?>

The for is a Repetition Structure, which, as the name suggests, is intended to perform a number of repetitions while the second parameter condition is met.

It is divided into three parts:

  • the start. In the case of $i = 1 is the initial definition value.
  • the condition for the repeat to continue running. In case, while $i is less than or equal to $abas.
  • What to do after performing an increment. In this case, $i++ increment +1 in $i for the next loop.

The excerpt <?= $i ?> will be in charge of printing the current value of $i in HTML.

In versions prior to 5.4 of PHP, you would have to use <?php echo $i; ?>.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.