This forum is now read-only. Please use our new forums at

For Loops in PHP Forum

View Course » View Exercise

609 points
Submitted by
about 5 years ago

Confused : $langs / $lang variables

I'd like some explanation about the code on line 15

 foreach ($langs as $lang)

Why isn't $lang introduces before ? I get that $langs is introduced line 11

 $langs = array("JavaScript",
      "HTML/CSS", "PHP",
      "Python", "Ruby");

But I $lang (without s) just seems to pop out of nowhere. I think I get what's happening, but I'd really like a confirmation.

In fact, line 15 could be telling something like :

"consider every item in $langs array as a value for a variable named $lang"

Thus line 15 is introducing the $lang variable. Could anybody confirm this ? That'd really be helpful.

2 votes


It's kind of like a universal operator.

The guys and gals over at Stack Overflow can explain much better than I ever could though!

431 points
Submitted by
about 5 years ago

1 Comment

51d461a27c82caf4fd0001bb_227070795 sh4ry about 5 years ago

Useful indeed. Thanks.

1 vote


Whatever is after the as in foreach ($array as $newVariable) is declared at that point.

It can be called whatever you want.

511 points
Submitted by
about 5 years ago

0 votes


In foreach, first variable is the array object. The example use $langs.

If you want to read each element of the array need to use an other variable. $lang

Something like

foreach($my_array as $an_element_of_array){
    echo $an_element_of_arrray;

538 points
Submitted by
over 4 years ago