Home >Backend Development >PHP Tutorial >A few conjectures about the array model in PHP (by misko lee)_PHP Tutorial
According to my personal understanding, arrays should be a continuous space in memory. Before using the array, a blank memory of a specified size needs to be opened in the memory. If the declared size is smaller than the available continuous memory size, a memory overflow error should be reported.
Children's shoes who have used PHP arrays should be able to quickly determine that arrays in PHP do not have the above characteristics. First, there is no need to determine the size of the array declaration; second, there is no upper limit for the use of the array. Through these two points, we can judge that the array in PHP is a loose structure of a linked list, not a continuous memory space.
Arrays in PHP can be divided into two forms: indexed arrays and associative arrays. Index array is a counting array structure. The associative array is an implementation of the map data structure, which is the key-value structure.
We will have some discussion about indexed arrays and associative arrays through the following examples.
$arr=array(1,2,3,'name'=>'misko_lee','age'=>22); //Define an indexed, associative mixed array
for($i=0;$i
The Cout($arr) function call returns the length of the $arr array. But the for loop can only output the index array normally. Therefore, we can judge that index arrays and associative arrays are two different implementations. This also proves the conjecture that arrays in PHP have a loose structure.
We also have the following conjectures about the index array:
$arr[100]=100;
$arr[]=101; //At this time, the index of $arr[] automatically increasing is 101.
The above experiment proved our conjecture. The array counter in PHP does not start counting from the first address of the array memory, but a pseudo counting method. Therefore, using a counter to determine the size of an array is completely wrong.
The above remarks are personal nonsense and are extremely unreliable. Seniors are welcome to point out errors. Good people have a safe life.
The last PS: After traversing the array using foreach, if it is not due to demand, please use the reset() function to reset the array pointer