Home >Backend Development >PHP Problem >How to modify the values of multiple elements in an array in php
Two modification methods: 1. Use array_splice() to replace the new value. The syntax is "array_splice(array, starting position, replacement number, replacement array)". The number of replacements and the number of elements in the replacement array must be consistent. 2. Use array_map() to call a user-defined function to modify one or more values.
The operating environment of this tutorial: windows7 system, PHP7.1 version, DELL G3 computer
php has many modification arrays Two methods for element values
Method 1: Use the array_splice() function to replace the array value
array_splice($array,$start,$length,$replacement)
Use the array_splice() function to replace the array value from Specify the position$start
Start replacing the specified number of array elements (the length value and the number of replacements need to be consistent)
Therefore, if multiple values are replaced, replace the value$ replacement
can be set to an array.
Example:
<?php $arr=array(1,2,3,4,5); var_dump($arr); array_splice($arr,1,3,array("A","B","D")); var_dump($arr); ?>
Method 2: Use the array_map() function to call a user-defined function to modify one or more values
array_map(myfunction,array)
array_map() function applies the user-defined function to each value in the array, and returns the array with the new value after the user-defined function is applied.
Example 1: Modify all array elements
<?php function f($num){ return($num+2); } $arr=array(1,2,3,4,5); var_dump($arr); var_dump(array_map("f",$arr)); ?>
Example 2: Double even numbers
<?php function f($num){ if($num%2==0){ return($num*$num); } return $num; } $arr=array(1,2,3,4,5); var_dump($arr); var_dump(array_map("f",$arr)); ?>
Recommended learning: "PHP video tutorial"
The above is the detailed content of How to modify the values of multiple elements in an array in php. For more information, please follow other related articles on the PHP Chinese website!