This article mainly and everyone to share the PHP array pointer in detail, first we will share with you the PHP array refers to the needle operation method, hope to help everyone.
One, PHP array pointer operation
Using PHP's built-in functions: Key,current,next (), prev () moves to the previous,
Reset () Resets, moves to the first element, end () moves to the last element
Note that once the pointer position is illegal, it is not possible to do relative movement (Next,prev), can be absolutely moved (reset,end), reset, use a higher frequency!
Each (), a collection of key,current, and next three functions! After you get the current element information, move the pointer over the next element!
Array of element information = each ($arr). Move pointer
Note that the array of element information is the two representations of the scheme: Index and association.
Where: Index: 0,1 for keys and values, association: Key,value for Keys and values, respectively
Second, the commonly used pointer traversal method
Each+while+list traversing an array
List-each traversing an array
Upgrade Operation:
You will get the key variables and the value variable operation, simplify!
Using the list structure
Take advantage of an indexed array and initialize multiple variables at the same time!
The return value of each contains the index array 0 for the key, and1 for the value!
using list -Simplified results:
In fact: As long as there is a loop structure, pointer operations can complete the traversal of the array
Three, the pointer problem of the array discussion
Consider the pointer position problem when copying:
What if the original array pointer is already illegal?
Look again:
The problem is, after copying, who first executes the current, which array pointer is initialized!
The cause of this behavior is:
1, if the array pointer position is illegal, the new array pointer will be initialized when copying!
2, when the value is passed, PHP uses a COW (copy on write) optimization measures!
Two points to copy when writing:
When a value is passed, it does not immediately open a value space for the new variable, and a value space is used before the two variables are changed.
Once a variable is changed, the value space is copied, allowing the variable to be changed to reference the new space!
Note that current also emits write operations, resulting in space being copied! First the current who, who is the new one, the pointer is initialized!
When foreach
1, traverse the copy instead of the original array!
2, a real copy is only possible if the original array has a write operation. The original array pointer stays at the current position, and if it is illegal, it is initialized!