foreach syntax

Most modern languages use very similar syntax inspired by C; but the features added since C are really non-standard! The “for-each” syntax annoys me particularly. I mean none of these is significantly better/worse than the others, but I program in all these languages (apart from C#) on a regular basis and I always have to think when typing in the line in order not to get the wrong syntax.

PHP foreach (list as element)
Perl foreach my element (list)
Java for (element : list)
Javascript for (var element in list)
C# foreach (element in list)

For what it’s worth, I think “foreach” is nicer than “for” as it reads more like a sentence (the word “for” really makes no sense at all in that context); and about “in” vs. colon I’ve got no preference really.

2 Responses to “foreach syntax”

  1. Robert Says:

    BTW, there’s `for each … in` since JS 1.6, see:
    https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Statements/for_each…in :)

  2. Flo Ledermann Says:

    You can add Python (where I am doing most of my work nowadays) with yet another slightly different syntax:


    for element in list:

    Btw: Python does not even know a C-style for loop, you can only iterate over lists there. An C-style for loop would be


    for i in range(n):

    Concerning the semantics of for vs. foreach: I believe in mathematics, when talking about sets you say “for all x in Y”, this even has a distinct sign (∀) – so “for” really is short for “for all”, not “for each” for people who have a math background.

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

For inserting HTML or XML please remember to use &lt; instead of <