Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between for and foreach?

Tags:

What is the major difference between for and foreach loops?

In which scenarios can we use for and not foreach and vice versa.

Would it be possible to show with a simple program?

Both seem the same to me. I can't differentiate them.

like image 756
CHANDRA Avatar asked Jun 07 '12 09:06

CHANDRA


People also ask

What's the difference between foreach and for?

foreach is useful when iterating all of the items in a collection. for is useful when iterating overall or a subset of items. The foreach iteration variable which provides each collection item, is READ-ONLY, so we can't modify the items as they are iterated. Using the for syntax, we can modify the items as needed.

Which is better for or foreach?

As it turned out, FOREACH is faster on arrays than FOR with length chasing. On list structures, FOREACH is slower than FOR. The code looks better when using FOREACH, and modern processors allow using it. However, if you need to highly optimize your codebase, it is better to use FOR.


1 Answers

a for loop is a construct that says "perform this operation n. times".

a foreach loop is a construct that says "perform this operation against each value/object in this IEnumerable"

like image 57
Dave Bish Avatar answered Oct 15 '22 08:10

Dave Bish