Cycling Through PHP Arrays using Pointers

Cycling Through PHP Arrays

When accessing the values of PHP arrays, looping them through foreach loops is not the only way. We can get individual values and keys of an array. There are invisible pointers in an array that tells the current position. We can cycle through them to get values at different positions of an array. We use current(), next(), prev(), end(), reset() and each() functions for cycling through the values/positions.

Here’s what those functions do:

current(): Access the value of the current array position.
next(): Move the invisible array pointer to the next position and access it as well.
prev(): Move the invisible array pointer to the previous position and access it.
end(): Move the invisible array pointer to the end of the array and access it.
reset(): Reset the array pointer i.e. move the pointer to the first array value and access the value.
each(): Access the current key as well as value of an array. The pointer is moved forward after they are accessed.

Example use of these statements to move the array pointers while printing them

each() function

This function is quite useful for looping through and accessing all the values one by one. The result of each function is stored as an array.

Here’s what each() does:

This function is used with list function to cycle through and access all the values of an array. Here’s how you do it:

You may also like

Comments are closed here.


Subscribe to Blog via Email

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Join 2 other subscribers