PHP loop X amount of times

后端 未结 8 1281
有刺的猬
有刺的猬 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).

提交回复
热议问题