The PHPforeach () function is only applicable to arrays. This is just a simple way to traverse arrays. The PHPforeach () function can only be used for arrays. an error occurs when you try to use it for another data type or an uninitialized variable. There are two types
This is just a simple way to traverse arrays. The PHP foreach () function can only be used for arrays. an error occurs when you try to use it for another data type or an uninitialized variable. There are two types of syntax. The second type is secondary, but it is the first type of useful extension.
Foreach (array_expression as $ value)
Statement
Foreach (array_expression as $ key => $ value)
Statement
The first format traverses the given array_expression array. In each loop, the value of the current unit is assigned to $ value and the pointer inside the array moves forward (so the next unit will be obtained in the next loop ).
In the second format, only the key names of the current unit are assigned to the variable $ key in each loop.
Objects may be traversed from PHP 5.
Note: When the PHP foreach () function is executed, the pointer inside the array automatically points to the first unit. This means that you do not need to call reset () before the foreach loop ().
Note: Unless the array is referenced, the PHP foreach () function operates on a copy of the specified array rather than the array itself. Therefore, the array pointer is not changed by the each () structure, and the modification to the returned array unit does not affect the original array. However, the internal pointer of the original array does move forward when processing the array. Assuming that the foreach loop is running till the end, the internal pointer of the original array points to the end of the array.
Since PHP 5, you can easily add & before $ value to modify the array unit. This method will assign values by reference instead of copying a value.
- < ?php
- $arr = array(1, 2, 3, 4);
- foreach ($arr as &$value) {
- $value = $value * 2;
- }
- // $arr is now array(2, 4, 6, 8)
- ?>
The PHP foreach () function is available only when the retrieved array can be referenced (for example, a variable ).
Bytes. The PHP foreach () function can only be used for arrays. an error occurs when you try to use it for another data type or an uninitialized variable. There are two types...