This article mainly introduces PHP array cursors to implement various operations on arrays, this article analyzes in detail the techniques used by the current and next methods in PHP array operations to control the movement of array cursors to achieve array traversal, for more information about how to use PHP array cursors, see the following example. We will share this with you for your reference. The details are as follows:
How does one implement loops on arrays without using foreach?
A: We only need to simulate foreach. when the array executes the foreach loop, there is a cursor pointing to the value of the current array loop,
If we can get the cursor and operate the cursor to forward or backward the cursor, then we can implement a circular array without foreach.
Code directly, clear and intuitive:
<? Php $ arr = array ('you', 'Ruby', 'an', 'haok', 'you', 'yes', 'Qing', 'day '); // current () function is used to obtain the value of the cursor's array position. // next () is used to move the cursor to the end of the array. for (; $ v = current ($ arr ); next ($ arr) {echo $ v ,'
';}/* Return. if you are fine, it will be sunny. * // then how can we take the cursor two steps and two steps? For (; $ v = current ($ arr);) {echo $ v ,'
'; Next ($ arr) ;}// execution result, no response. why? // The cause is that the previous cyclic cursor has reached the tail of the array. // therefore, when executing current ($ arr), false is always returned, // therefore, the second loop will not be executed // Here we will use a reset () method to re-point the cursor to the array's header reset ($ arr); echo'
'; For (; $ v = current ($ arr);) {echo $ v ,'
'; Next ($ arr) ;}// then how can we take two steps and take a step back? Reset ($ arr); echo'
'; For ($ flag = true; $ v = current ($ arr);) {echo $ v ,'
'; If ($ flag) {next ($ arr); $ flag = false;} else {prev ($ arr ); $ flag = true;}/* returns the result. if you are well-protected, the weather is fine. * // How can you reverse the cycle? // The end () function is used here to point the cursor of the array to the end ($ arr); echo'
'; For (; $ v = current ($ arr); prev ($ arr) {echo $ v ,'
';}/* Returned: the sky is fine. if you * // note that when the array value is equal to 0, false, null, undefined, the second part of the for loop returns false, which causes the loop to terminate reset ($ arr); echo'
'; $ Arr2 = array ('you', 'Ruby', 0, 'haok', 'you', 'yes', 'Qing', 'day '); for (; $ v = current ($ arr2); next ($ arr2) {echo $ v ,'
';}/* Returns if */?>
In addition, you can use the key () function to obtain the keys pointed to by the cursor.