0
What is the use of foreach loop?
it is used only for arrays?. how does the loop works can any one explain in detail?
2 ответов
+ 2
best source (with examples):
http://php.net/manual/en/control-structures.foreach.php
+ 2
Not familiar with php but in general:
a foreach loop is a more concise way to iterate though a container of some sort (array, list, set, etc)
instead of manually initializing a counter variable and telling it how to iterate, the foreach will give you the actual item that is being looped over.
So take this example:
//iterate through a container using a for
for (int i= 0; i < container.size (); ++i){
cout << container [i] ;
}
//now the foreach
for (i : container) {
cout << i; // i will be equal to container [0] on the first iteration, then container [1] and so on
}