PHP arrays are still commonly used. So I studied PHP array loop operations and shared them here, hoping to be useful to you. PHP is basically an array language. There are often a lot of PHP array loop operations, mainly in two ways, one is foreach, the other is while, which is good or bad is always controversial, although I have been aware of this problem for a long time, I have not studied it in detail. I have been ignorant of it until now. To save some CPU time in the future, I will summarize it as follows:
When the array "read" operation is performed in the loop, the foreach is faster than while, And the PHP array loop operation has no format to view and print the code to the clipboard?
- foreach($arrayas$value){
- echo$value;
- }
- while(list($key)=each($array)){
- echo$array[$key];
- }
- foreach($arrayas$value){
- echo$value;
- }
- while(list($key)=each($array)){
- echo$array[$key];
- }
When the array "write" operation is performed in a loop, while is faster than foreach:
No format to view printed code copied to the clipboard?
- foreach($arrayas$key=>$value){
- echo$array[$key]=$value.'...';
- }
- while(list($key)=each($array)){
- $array[$key]=$array[$key].'...';
- }
- foreach($arrayas$key=>$value){
- echo$array[$key]=$value.'...';
- }
- while(list($key)=each($array)){
- $array[$key]=$array[$key].'...';
- }
Conclusion: foreach is usually considered to be slower than while when it involves value replication, but in fact, if it is just a read operation on the array in a loop, foreach is very fast, this is because the replication mechanism adopted by PHP is "reference replication, write copy". In this way, it is not difficult to understand the efficient read operations of foreach. In addition, since foreach is not suitable for Array write operations, we can draw a conclusion that, in most cases, it is similar to foreach ($ arrayas $ key => $ value) all code in the form should be replaced with while (list ($ key) = each ($ array )).
The speed differences produced by these techniques may not be obvious in small projects, but in large projects like frameworks, a single request may involve hundreds of thousands of array loop operations, the difference is obviously magnified.