The difference between for and foreach in PHP

  • 2020-03-31 21:35:01
  • OfStack

Note: unless the array is referenced, foreach is manipulating a copy of the specified array, not the array itself. Therefore, the array pointer is not changed by the each() structure, and modifications to the returned array cells do not affect the original array.

1. Starting with php5, foreach may also traverse the properties of the object.
2. Starting with php5, foreach can easily modify the cell of an array by adding an & before $value, which assigns a value by reference instead of copying it.
 
<?php 
$arr = array(1, 2, 3, 4); 
foreach ($arr as &$value) { 
$value = $value * 2; 
} 
?> 
 The output :$arr=array(2, 4, 6, 8) 

Note: foreach does not support the ability to suppress error messages with "@".

Related articles: