How to get variable and print multiple "li" according to variable number?

0

I have a $abas = 4 variable.

I need PHP to make a echo in the variable number, in which case it would be 4 echos.

The result should be:

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

I'm a beginner in PHP, what's the best way to do this?

    
asked by anonymous 28.08.2018 / 21:10

1 answer

7

For what you want to do, I recommend using for .

Example:

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

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

It is divided into three parts:

  • the beginning. In case $i = 1 is the initial setting value.
  • the condition for the replay to continue running. In this case, while $i is less than or equal to $abas .
  • What to do after incrementing. In this case, $i++ increments +1 in $i to the next loop.

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

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

    
28.08.2018 / 21:13