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 trialJeremiah Allen
14,627 PointsPHP loops: scope of var's?
This may be covered later in the track but I was wondering if a variable declared or altered in a loop is only usable inside the loop (like JS) or if they behave differently in PHP. They seem to act differently but I might just be confusing myself.
I apologize if I have some terminology incorrect here.
1 Answer
Ryan Field
Courses Plus Student 21,242 PointsHi Jeremiah,
You're correct. In PHP, a variable declared inside a loop (or function, for that matter) is only available within that scope. Unlike JavaScript, however, variables declared in the global scope are not available in the function scope in PHP. You can access/alter global variables within a function scope, but you need to specifically state that you are referencing the global variable using the 'global' keyword.