PHP loop X amount of times

后端 未结 8 1174
有刺的猬
有刺的猬 2020-12-17 17:55

I have a string called $columns which dynamically gets a value from 1 to 7. I want to create a loop of for however many times

相关标签:
8条回答
  • 2020-12-17 18:20
    for ($k = 0 ; $k < $columns; $k++){ echo '<td></td>'; }
    
    0 讨论(0)
  • 2020-12-17 18:25

    If $columns is a string you can cast to int and use a simple for loop

    for ($i=1; $i<(int)$columns; $i++) {
       echo '<td></td>';
    }
    
    0 讨论(0)
  • 2020-12-17 18:26

    Here's a more readable way to achieve this:

    foreach(range(1,$columns) as $index) {
       //do your magic here
    }
    
    0 讨论(0)
  • 2020-12-17 18:28

    You can run it through a for loop easily to achieve this

    $myData = array('val1', 'val2', ...);
    
    for( $i = 0; $i < intval($columns); $i++)
    {
        echo "<td>" . $myData[$i] . "</td>";
    }
    
    0 讨论(0)
  • 2020-12-17 18:36

    If you just need to use number of repeat count:

    for ($i = 0; $i < 5; $i++){
        // code to repeat here
    }
    
    0 讨论(0)
  • 2020-12-17 18:39

    A for loop will work:

    for ($i = 0; $i < $columns; $i++) {
        ...
    }
    
    0 讨论(0)
提交回复
热议问题