Differences between a while loop and a for loop in PHP?

前端 未结 6 2061
梦谈多话
梦谈多话 2020-12-06 12:02

I\'m reading an ebook on PHP right now, and the author noted that the difference between a while loop and a for loop is that the for loop will count how many times it runs.<

6条回答
  •  醉梦人生
    2020-12-06 12:19

    "For" expresses your intentions more clearly

    Functionally, your two examples are the same. But they express different intentions.

    • while means 'I don't know how long this condition will last, but as long as it does, do this thing.'
    • for means 'I have a specific number of repetitions for you to execute.'

    You can use one when you mean the other, but it's harder to read the code.

    Some other reasons why for is preferable here

    • It's more concise and puts all the information about the loop in one place
    • It makes $i a local variable for the loop

    Don't forget foreach

    Personally, the loop I use most often in PHP is foreach. If you find yourself doing things like this:

    for ($i=0; $i < count($some_array); $i++){
      echo $some_array[$i];
    }
    

    ...then try this:

    foreach ($some_array as $item){
       echo $item;
    }
    

    Faster to type, easier to read.

提交回复
热议问题