Traversal replacement steps: 1. Use the foreach statement to traverse the array by referencing the loop, the syntax is "foreach($arr as $k=>&$v){//Loop body statement block;}"; 2. In the loop body, use the "===" operator to find the elements of the specified field and reassign the value. The syntax "foreach($arr as $k=>&$v){if($k===specifies Field value){$v=replacement value;}}".
The operating environment of this tutorial: windows7 system, PHP8.1 version, DELL G3 computer
In the php array, you can use the foreach statement to Traverse and replace the value of a certain field (key name).
Implementation steps:
Step 1: Use the foreach statement to traverse the array through reference loops
foreach ($array as $key => &$value){ //循环体语句块; }
Traverse the given The $array array will assign the value of the current array to $value and the key name to $key in each loop.
Generally, when using the foreach statement to traverse an array, it operates on the backup of the array and generally does not affect the array itself.
If you want to change the array through a loop, you can 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 within the loop body will affect the array itself.
Step 2: In the loop body, use the "===" operator to find the specified field and reassign the value
if($key===指定字段){ $value=新值; }
Complete example Code:
<?php header(&#39;content-type:text/html;charset=utf-8&#39;); function f($arr,$s,$r){ foreach($arr as $k=>&$v){ if($k===$s){ $v=$r; } } echo "字段 $s 的值替换为 $r"; var_dump($arr); } $arr=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow"); echo "原数组:"; var_dump($arr); f($arr,"a","aaa"); f($arr,"b","bbb"); f($arr,"c","ccc"); ?>
It can be seen that there is an & before the last element. That is because the $value reference of the last element of the array is after the foreach loop. Will remain. We need to use unset() to destroy it.
unset($v); // 最后取消掉引用
Recommended learning: "PHP Video Tutorial"
The above is the detailed content of How to traverse and replace the value of a certain field (key name) in a php array. For more information, please follow other related articles on the PHP Chinese website!