Home  >  Article  >  Backend Development  >  How to use foreach statement to modify key value in php

How to use foreach statement to modify key value in php

青灯夜游
青灯夜游Original
2021-09-03 10:09:482119browse

Modification method: 1. Use the "foreach ($array as &$value)" statement to traverse the array, and assign the key value of the current array to the variable "$value" in each loop; 2. In the loop In the body, use the "$value=new value;" statement to assign the value on the right to the variable "$value" on the left.

How to use foreach statement to modify key value in php

The operating environment of this tutorial: windows7 system, PHP7.1 version, DELL G3 computer

foreach is specially designed for Statements designed to traverse arrays are commonly used methods when traversing arrays, and provide great convenience in traversing arrays; after PHP5, objects can also be traversed (foreach can only be applied to arrays and objects).

The foreach statement traverses the array regardless of the array subscript, and can be used for discontinuous index arrays and associative arrays with strings as subscripts.

When the foreach statement loops, the pointer inside the array will move forward one step, so that the next array element will be obtained in the next loop until the end of the array is traversed, the traversal stops and the loop exits.

How to use foreach statement to modify key value in php?

<?php
$array= array(1,2,3,4,5,);
foreach ($array as &$value) { 
    $value = $value*2;  // 元素值乘以2
}
unset($value); // 最后取消掉引用
var_dump($array)
?>

Output result:

How to use foreach statement to modify key value in php

Explanation: Add & before $value so that the foreach statement will assign by reference instead of Copying a value and operating on the array within the loop body will affect the array itself.

Note: The $value reference of the last element of the array will still be retained after the foreach loop. We need to use unset() to destroy it.

Recommended learning: "PHP Video Tutorial"

The above is the detailed content of How to use foreach statement to modify key value in php. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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