The for loop only has limited number indexes. After the for and foreach traversal ends, you do not need to reset () The data for next traversal, while the each method requires
<? Php tutorial
//
$ Arr = array ('A' => 'abc', 'B' => 123, 'c' => true );
// B
// $ Arr = range ('A', 'D ');
// 1
For ($ I = 0; $ I <sizeof ($ arr); $ I ++)
Echo $ arr [$ I]. ',';
Echo '<br/> ';
// 2
Foreach ($ arr as $ key)
Echo "$ key ,";
Echo '<br/> ';
// 3
Foreach ($ arr as $ key => $ val)
Echo "$ key-$ val ,";
Echo '<br/> ';
// 4
Reset ($ arr );
While ($ item = each ($ arr )){
Echo $ item ['key']. '-'. $ item ['value']. ',';
}
Echo '<br/> ';
// 5
Reset ($ arr );
While (list ($ key, $ val) = each ($ arr )){
Echo "$ key-$ val ,";
}
Echo '<br/> ';
?> Use the Statement a $ arr = array ('A' => 'abc', 'B' => 123, 'c' => true ); initialize $ arr to obtain the numeric index array. The output is as follows:
,,,
Abc, 123, 1,
A-abc, b-123, C-1,
A-abc, b-123, C-1,
A-abc, b-123, C-1, use the statement B $ arr = range ('A', 'D'); initialize $ arr to get the associated array, the output is as follows:
A, B, c, d,
A, B, c, d,
0-a, 1-b, 2-c, 3-d,
0-a, 1-b, 2-c, 3-d,
0-a, 1-b, 2-c, 3-d,
After repeated tests, the results show that for traversing the same array, foreach is the fastest, while is the slowest. Foreach is about 20% ~ Faster than while ~ About 30%. Then add the array subscript to 500000 and 5000000. However, in principle, foreach operates on the array copy (by copying the array), while moves the internal indicator of the array. In general logic, while should be faster than foreach (because foreach first copies the array when starting execution, while directly moves the internal indicator .), But the result is just the opposite. The reason should be that foreach is implemented internally in PHP, while is a general loop structure.