Difference between PHP for and foreach

First, we prepare two arrays for traversal:

$arr1=array(1=>'a', 3=>22, 5=>'b', 4=>'c', 8=>'d');

$arr2=array('a'=>'aaa', 'b'=>'bbb', 'c'=>'ccc', 'd'=>'ddd', 'e'=>'eee');

 

One: for loop structure

Loop 1:

for($i=0,$num=count($arr1);$i<$num;$i++){

    echo $arr1[$i].' ';

}

Output result: a 22 c

Loop 2:

for($i=0,$num=count($arr2);$i<$num;$i++){

    echo $arr2[$i].' ';

}

This statement has no output

 

analyze:

Loop 1 prints only the first two elements of the array $arr1, while $arr2 in loop 2 prints nothing.

The reason is that the for loop is incremented by numbers, so for can only access arrays whose keys are numbers. For example, loop 1 increments and accesses cells with keys 0 to 4 in the $arr1 array according to $i=0 to $i=4 , but the keys in that array are: 1,3,5,4,8. And array units with key values ​​exceeding 4 (5=>'b', 8=>'d') will not be accessed, because count($arr1)=5, so $i<5; so the final output is only: a 22 c ; all keys in $arr2 are characters, not numbers, so there is no output in loop 2.

 

Two: foreach loop structure

Loop 3:

foreach($arr1 as $key=>$value){

    echo $key.'=>'.$value.' ';

}

Output result: 1=>a 3=>22 5=>b 4=>c 8=>d

Loop 4:

foreach($arr2 as $key=>$value){

    echo $key.'=>'.$value.' ';

}

Output result: a=>aaa b=>bbb c=>ccc d=>ddd e=>eee

analyze:

The foreach loop structure loops according to the pointer inside the array. When the foreach starts to execute, the pointer inside the array will automatically point to the first unit. So the next time through the loop will get the next cell, no need to traverse the entire array by the array key. This is also the difference between foreach and for. Of course, foreach can only be used on arrays and objects , and since foreach relies on an internal array pointer, modifying its value in a loop will likely cause unexpected behavior.

 

Note: for each loop operates on the value under the corresponding index, and changes to each value will also be reflected in the traversed object. Each time foreach operates a unit, it takes its index and value into variables respectively, or only takes the value into one variable, and then operates the variable with index and value separately, without affecting the traversed object itself . If you want to modify the value in the object during the traversal process, you need to add the ampersand before the variable in the declaration. For example: foreach($array as &$value).

 

Conclusion: If an array is to use consecutive numbers as the keys of the array elements, then the for loop structure can be used. If you are not sure about the keys of the array or if the keys of the array contain characters, you should use the foreach loop structure.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325241358&siteId=291194637