Jump to content

foreach() in PHP


Guest vegras

Recommended Posts

Guest vegras

this is my first post here, so hi. i decided to get around to learning PHP last night, since i'm getting tired of ASP... one of the first problems i ran into in my code was getting the current array position inside a foreach() loop based on that same array. i'm not sure why, but key() was returning the value of the array element instead of the array position, or something weird like that. anyhow, i talked to some fine people who knew the language much better than i do, and was informed about another way of calling the function:foreach($x as $y => $z) { };where $x is the array foreach() is looping through, $y is the current element's position/index value, and $z is the current element's data value. given that it gives you extremely easy access to the index without calling another function on every pass of the loop, i was rather surprised to learn it wasn't in the PHP Loops tutorial. so i'd like to suggest it be added, although you may have guessed that. :)[edit: the comma between $x and $y should have been "as", thanks DTP]

Link to comment
Share on other sites

Are you sure it can be called like that? Because I've learned it this way:

foreach ($array as $key => $value) {}
In the javascript tutorial this loop wasn't explained from the beginning either :)
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...