1. 24
    Use an array key to determine current iteration
    1m 26s

Use an array key to determine current iteration

Mark Shust
InstructorMark Shust
Share this video with your friends

Social Share Links

Send Tweet
Published 2 years ago
Updated 2 years ago

One can expand on PHP's foreach loop by using array indexes, which allow you to control the location of PHP elements.

Instructor: [0:00] Creating a list of tags, we only define the values of the tags. Even though we did not explicitly define them, keys also exist within arrays.

[0:10] If we don't define them, keys are created for us automatically and they are zero -based, which means they start at . The first value of this loop is PHP, and its key is . The second one has a key of 1, and the third one has a key of 2. The key of a value is always one less than the number of the value within the array.

[0:33] We can access the key within a foreach loop by passing it in as a first value right after this as. This can be any arbitrary variable name again, but it's common to use the name key. Then before this tag variable is defined, we will place an equal sign and a greater sign operator. This is an assignment operator that is commonly used with arrays.

[0:58] Then let's go ahead and move to our echo tag and we will output this key followed by a colon. When we save and refresh the page, we will see evidence of the zero-based array. It's easy to remember this format as foreach array as key = value. Dollar sign value is often used as the iterator value within loops.

egghead
egghead
~ 15 minutes ago

Member comments are a way for members to communicate, interact, and ask questions about a lesson.

The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io

Be on-Topic

Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.

Avoid meta-discussion

  • This was great!
  • This was horrible!
  • I didn't like this because it didn't match my skill level.
  • +1 It will likely be deleted as spam.

Code Problems?

Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context

Details and Context

Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!

Markdown supported.
Become a member to join the discussionEnroll Today