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

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.