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 trialJeremy Frimond
14,470 Pointsforeach loop conceptual question with variables
If I have the array variable $letters and want to code a foreach loop why do i include a second variable that is singular for example:
foreach ($letters as $letter) {echo "AB"; }
Additionally, when fooling around I notice that I can get the same result via coding:
foreach ($letters as $pumpkins) {echo "AB"; }
What is the significance of the second $variable, what does it do ?>
2 Answers
Stone Preston
42,016 Pointsthat variable is known as a "working variable". the for each loop lets you loop through an array, but you need a way to reference the object in the array the loop is currently at and the working variable accomplishes this. Without that variable, you have no way of accessing the item in the array.
for example if we wanted to print out each letter in an array of letters called $letters that spells "cat" :
foreach ($letters as $letter) {echo $letter; }
without the working variable $letter, we wouldnt be able to print out each individual letter in the array
Prathom Satapronpinyo
12,759 Pointsforeach loop works only on arrays and objects
foreach loop will go through the array variable and assigned value of the current element to a second variable which can be declared as anything but in the correct syntax and the internal array pointer is advanced by one (so on the next iteration, you'll be looking at the next element).