How to count inverse with for in php?

后端 未结 4 609
甜味超标
甜味超标 2021-01-02 02:15

My Problem: I want to count inverse in the for loop.

This is the opposite of what I want to do:

for($i=1;$i<=10;$i++){
          


        
4条回答
  •  再見小時候
    2021-01-02 02:57

    If you take the for as you wrote and just replace $i++ with $i--, the value of $i will be decremented with every iteration (1, 0, -1, -2, etc.) and the looping condition $i<=10 is always true.

    If you want to count backwards, you also need to change the other parts (initialization and looping condition):

    for ($i=10; $i>=1; $i--){
        echo $i;
    }
    

    Or you take the last and subtract the current value from it and add the first value to it:

    for ($first=1, $i=$first, $last=10; $i<=$last; $i++){
        echo $last - $i + $first;
    }
    

提交回复
热议问题