Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP loop X amount of times

Tags:

loops

php

I have a string called $columns which dynamically gets a value from 1 to 7. I want to create a loop of <td></td> for however many times the value of $columns is. Any idea how I can do this?

like image 909
Ahmed Avatar asked Feb 03 '13 11:02

Ahmed


People also ask

How many times loop will be executed in PHP?

PHP supports following four loop types.

How can I print 1 to 10 numbers in PHP?

We can print numbers from 1 to 10 by using for loop. You can easily extend this program to print any numbers from starting from any value and ending on any value. The echo command will print the value of $i to the screen. In the next line we have used the same echo command to print one html line break.

How do you repeat a loop in PHP?

do... while - loops through a block of code once, and then repeats the loop as long as the specified condition is true. for - loops through a block of code a specified number of times. foreach - loops through a block of code for each element in an array.


2 Answers

for ($k = 0 ; $k < $columns; $k++){ echo '<td></td>'; }
like image 139
Fatih Donmez Avatar answered Oct 13 '22 18:10

Fatih Donmez


Here's a more readable way to achieve this:

foreach(range(1,$columns) as $index) {
   //do your magic here
}
like image 29
murze Avatar answered Oct 13 '22 19:10

murze