Implementation steps: 1. Use the foreach statement to traverse the array in a reference loop, with the syntax "foreach ($array as &$value){//loop body statement block;}"; 2. In the loop body , use the "/=" operator to divide all array elements by 2, the syntax is "$value /= 2;", so that after the loop ends, each element in the array will change.
The operating environment of this tutorial: Windows 7 system, PHP version 8.1, DELL G3 computer
In PHP, you can use the foreach statement to reference Modify the array elements in a loop by dividing each element in the array by 2.
Implementation steps:
Step 1: Use the foreach statement to traverse the array in a reference loop
foreach ($array as &$value){ //循环体语句块; }
Iterate over the given $array array, assigning the value of the current array to $value in each loop.
Use a reference loop (add & before $value, so that the foreach statement will assign a value by reference instead of copying a value), then operating on the array in the loop body will affect the array itself.
Step 2: In the loop body, use the "/=" operator to divide all array elements by 2
$value /= 2;
Wait for the loop to end, then the array The elements will all change.
Operation | Symbol | Example | Expansion form | Meaning |
---|---|---|---|---|
Divide | /= | $a /= 2 | $a = $a / 2 | Change the left side of the operator The value of the variable divided by the expression on the right is assigned to the variable on the left |
Complete example code:
<?php header('content-type:text/html;charset=utf-8'); $arr=array(2,4,6,8,10,12,14,16,18,20); echo "原数组:"; var_dump($arr); foreach($arr as &$value){ $value /= 2; } unset($value); // 最后取消掉引用 echo "数组元素都除以2后:"; var_dump($arr); ?>
Description:
Use the foreach statement to traverse the array in a reference loop. The $value reference of the last element of the array will still be retained after the foreach loop, so there will be a # before the last element. ##&
unset($value); The statement cancels the reference.
PHP Video Tutorial"
The above is the detailed content of How to divide each element in an array by 2 in php. For more information, please follow other related articles on the PHP Chinese website!