: This article mainly introduces the efficiency comparison of array_walk and foreach and for. for more information about PHP tutorials, see. The efficiency of array_walk, foreach, and for is determined by a small program, and the following results are found through the small program:
1. foreach is much more efficient than for, indicating that php has optimized the foreach function. if colleagues can use for and foreach, we recommend using foreach.
2. if you want to call a function in a loop, it is best to use array_walk.
& $ V) {$ temp = $ temp + 1 ;}$ t2 = microtime (true); $ t = $ t2-$ t1; echo "using foreach does not cost array operations: {$ t} \ n"; $ t1 = microtime (true); foreach ($ test_arr as $ k => & $ v) {$ v = $ v + 1 ;}$ t2 = microtime (true); $ t = $ t2-$ t1; echo "use foreach to operate the array directly: {$ t} \ n "; $ t1 = microtime (true); foreach ($ test_arr as $ k = >&$ v) {addOne ($ v );} $ t2 = microtime (true); $ t = $ t2-$ t1; echo "use foreach to call functions to operate on arrays: {$ t} \ n"; $ t1 = microtime (True); array_walk ($ test_arr, 'addone'); $ t2 = microtime (true); $ t = $ t2-$ t1; echo "cost for using array_walk: {$ t} \ n "; function addOne (& $ item) {$ item = $ item + 1 ;}?>Result:
Use for, no cost for array operation: 0.348432064056
Use for and directly perform operations on the array: 0.493929862976
Use for to call functions for Array Operations: 1.49323606491
No array operation cost for using foreach: 0.33071398735
Use foreach to directly operate on arrays: 0.337166070938
Use foreach to call the function to operate on the array: 1.13249397278
Cost for array_walk: 1.2829349041
The above describes the efficiency comparison of array_walk and foreach and for, including some content, and hope to help those who are interested in PHP tutorials.