What is the use of foreach loop? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
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?

31st May 2017, 8:40 AM
Champs
2 Answers
31st May 2017, 8:53 AM
Michal
Michal - avatar
+ 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 }
31st May 2017, 5:22 PM
Sean Patrick Franklin
Sean Patrick Franklin - avatar