Loops + Arrays = ForEach


#1

My code doesn't exactly behave incorrectly, however, I just don't understand why we define "$langs as $lang."
I get the loop "foreach" idea, but it seems like we could just not re-define $langs as $lang, especially not if we unset $lang after.. anyone got a simple explanation? (n00b here lol).

 foreach ($langs as $lang) {
              echo "<li>$lang</li>";
          }

#2

the work is now done for you, in each run of the loop, foreach will assign the next value in the array to $lang, and then you can print this value. $lang is updated in each run of the loop, foreach is taking care of it.


#3

Hey @helle2016 you can call $langs anything you want.....

 foreach ($whatever as $lang) {
              echo "<li>$whatever</li>";
          }

#4

yes, you can, if you do it correctly:

foreach ($langs as $whatever) {
    echo "<li>$whatever</li>";
}

#5

Whatever dude..... its been long since i did PHP.


#6

Giving wrong code examples can be really confusing for the learner.


#7

but why define langs as whatever in the first place? it seems that this is an extra step.Is it that i will use "whatever" in another place at times, perhaps?

To me it seems as if i define "today" as "Monday" in this example, when "today" would suffice to make things work


#8

$langs contains the array, $lang contains (in turn) the items in the array, so it most certainly useful.