Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

PHP PHP Functions PHP Internal Functions PHP Array Functions

Bruno Dias
Bruno Dias
10,554 Points

Why there are two variables at array_keys loop?

Why we have two variables on the loop used on the video?

foreach(array_keys($names) as $name){
  echo "Hello, $name<br/>";
};

We have $names and $name. Does that mean we storing the second value inside the $name variable?

2 Answers

Kevin Korte
Kevin Korte
28,149 Points

So it's doing something like this.

$names would likely be a key value array, something like

$names=array("student"=>"Jim","student"=>"Pam","teacher"=>"Robert")

Now, where calling a function inside a function, so first the array_key will return to use just the keys. So key => value becomes just ("student", "student", "teacher").

Now we passing our foreach a $names array that is just ``array("student", "student", "teacher"), and with every foreach, we need a working variable. It's very common to see that a variable containing an array is plural, like $names, and the working variable is the singular of that, or $name. For each item in the array we loop, so the first student key gets pulled out into the $name variable, and inside the loop we do something with $name. In this case we echo, so it would say "Hello, student", than it loops and grabs the second key, student again, and would echo a second time, "Hello, student", and it would than loop a third time, this time it would echo "Hello teacher".

The $name variable in the foreach loop is only available to the foreach loop, so when the foreach loop ends, so does access to the $name variable. But you would retain access to the $names variable that held the array.

Mike Costa
Mike Costa
Courses Plus Student 26,362 Points

Just pointing this out, but you can't have 2 keys with the same name. If you had this array:

$names = [
   "student"=>"Jim",
   "student"=>"Pam",
   "teacher"=>"Robert"
];

....the first "student" key would be overwritten. If you var dump this array you'll see:

array(2) {
  ["student"]=>
  string(3) "Pam"
  ["teacher"]=>
  string(6) "Robert"
}
Michael Caley
Michael Caley
5,376 Points

$names is an array, it contains all of the data.

Using the foreach command we pass the value stored in each key of the array through to $name one at a time.

If we then use array_keys we instead pass the key rather than the value to the variable $name.