PHP loop X amount of times

后端 未结 8 1175
有刺的猬
有刺的猬 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:40

    I like this way:

    while( $i++ < $columns ) echo $i;
    

    Just bear in mind if $columns is 5, this will run 5 times (not 4).

    Edit: There seems to be some confusion around the initial state of $i here. You are welcome to initialise $i=0 beforehand if you wish. This is not required however as PHP is a very helpful engine and will do it for you automatically (tho, it will throw a notice if you happen to have those enabled).

    0 讨论(0)
  • 2020-12-17 18:45

    just repeat $n times? ... if dont mind that $n goes backwards... the advantage is that you can see/config "times" at the beginning

    $n = 5;
    while (--$n >= 0)
    {
      // do something, remember that $n goes backwards;
    }
    
    0 讨论(0)
提交回复
热议问题