Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

PHP

Jeremy Frimond
Jeremy Frimond
14,470 Points

foreach 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
Stone Preston
42,016 Points

that 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
Prathom Satapronpinyo
12,759 Points

foreach 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).