For vs Foreach – Difference between For and Foreach
You must familiar with all loops if you are a programmer/developer. There are so many loops available and you can select appropriate one when you develop an application. I found For and Foreach loops almost same. I googled for finding the difference between For and Foreach(For Vs Foreach) but didn't get any clear idea. Here i am sharing my knowledge about some of difference between For and Foreach loop.
For can be used to run statements for a fixed number of times, foreach can be used to run statements for dynamically generated arrays(may be result of database query).We can also used for loop for dynamically generated array(may be result of database query) but foreach is the ideal way to iterate dynamic array. The reason behind this, we don't know the index of array as it may be associate result from database query. So if we use foreach than it will iterate the result one by one.
Look at below links for more results.
In Summary, For loop can be more optimized if we know the count of array and index of array while foreach is better when we have dynamic array without knowing index of array and size of an array.