Home > Backend Development > PHP Problem > How to modify the values ​​of multiple elements in an array in php

How to modify the values ​​of multiple elements in an array in php

青灯夜游
Release: 2023-03-16 08:40:01
Original
1841 people have browsed it

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.

How to modify the values ​​of multiple elements in an array in php

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

Use the array_splice() function to replace the array value from Specify the position$startStart 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);
?>
Copy after login

How to modify the values ​​of multiple elements in an array in php

Method 2: Use the array_map() function to call a user-defined function to modify one or more values

array_map(myfunction,array)
Copy after login

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

How to modify the values ​​of multiple elements in an array in php

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

How to modify the values ​​of multiple elements in an array in php

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!

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