0503 The difference between for and foreach in php

in conclusion:

foreach: can only be used for arrays and objects, if it is a non-indexed array, only foreach can be used.

for: If it is an indexed array, it can be traversed with for.

 

The foreach loop structure loops according to the pointer inside the array. When the foreach starts to execute, the pointer inside the array will automatically point to the first unit. So the next time through the loop will get the next cell, no need to traverse the entire array by the array key. This is also the difference between foreach and for. Of course, foreach can only be used on arrays and objects , and since foreach relies on an internal array pointer, modifying its value in a loop will likely cause unexpected behavior.

 

Each time the for loop operates on the value under the corresponding index, the change of each value will also be reflected in the traversed object. Each time foreach operates a unit, it takes its index and value into variables respectively, or only takes the value into one variable, and then operates the variable with index and value separately, without affecting the traversed object itself . If you want to modify the value in the object during the traversal process, you need to add the ampersand before the variable in the declaration. For example: foreach($array as &$value).

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325251590&siteId=291194637