Looking to Build/Redesign a Website or Blog ?

To speak to Rakshit, call +91 968 704 2303

For vs Foreach – Difference between For and Foreach

Hello Friends,

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.

Foreach will works only and only with arrays.For will works for any logical operation and i will continue until given condition fails.There is not much execution time difference. They works almost same way and same speed as foreach loop will takes time for getting next element while iterating array while for loop will takes time to re-initialize the variable.

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.

To know more about programming,JavaScript issues,jQuery,Expression Engine,MYSQL database,php info,php editor,programming php,Open-source,php help and php script , subscribe to our feed by entering email address below. You will get updates via email about every tutorial posted on this site . It will not take more than a sec.

Enter your email address:
Feel free to ask any question. Just leave your comment below and we will answer your comment with in 24 hours.


Leave a Reply

Your email address will not be published.