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

For Loops in PHP Forum

View Course » View Exercise

609 points
51d461a27c82caf4fd0001bb_227070795
Submitted by
sh4ry
over 4 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

permalink

It's kind of like a universal operator.

http://stackoverflow.com/questions/5720260/as-operator-in-php

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

431 points
A7145cd76586d8d777cb52b24af54549?s=140&d=retro
Submitted by
Erestyn
over 4 years ago

1 Comment

51d461a27c82caf4fd0001bb_227070795 sh4ry over 4 years ago

Useful indeed. Thanks.


1 vote

permalink

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

It can be called whatever you want.

511 points
4b213e0072e7b747653529cce5ca8072?s=140&d=retro
Submitted by
command_z
over 4 years ago


0 votes

permalink

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
919ddc943ca721fa46eca5228ea37ee3?s=140&d=retro
Submitted by
Ignacio
almost 4 years ago