How to divide each element in an array by 2 in php

青灯夜游
Release: 2023-03-16 15:24:02
Original
2433 people have browsed it

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.

How to divide each element in an array by 2 in php

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){
    //循环体语句块;
}
Copy after login

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;
Copy after login

Wait for the loop to end, then the array The elements will all change.

OperationSymbolExampleExpansion formMeaning
Divide/=$a /= 2$a = $a / 2Change 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(&#39;content-type:text/html;charset=utf-8&#39;);   
$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);
?>
Copy after login

How to divide each element in an array by 2 in php

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. ##&

How to divide each element in an array by 2 in php

unset($value); The statement cancels the reference.

Recommended learning: "

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template