Home  >  Article  >  Backend Development  >  How to modify a value in an array in php

How to modify a value in an array in php

青灯夜游
青灯夜游Original
2022-05-09 19:49:012310browse

Two modification methods: 1. Access the specified array element and reassign the value, the syntax is "array name [subscript] = new value;" or "array name ["key name"] = new value;"; 2. Use array_splice() to replace a specified element starting from the specified position, the syntax is "array_splice(array, starting position, 1, replacement value)".

How to modify a value in an array in php

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

php modification array Two methods for a value

Method 1: Access the specified array element and reassign the value

Syntax:

数组名[下标]=新值; //索引数组
数组名["键名"]=新值; //关联数组

Example 1:

<?php
$arr=array(1,2,3,4,5,6);
var_dump($arr);
$arr[2]="h";
var_dump($arr);
?>

How to modify a value in an array in php

Example 2:

<?php
$arr=array("a"=>"red","b"=>"green","c"=>"blue");
var_dump($arr);
$arr["b"]=23;
var_dump($arr);
?>

How to modify a value in an array in php

Method 2: Using array_splice()

Use array_splice() to modify a value in the array by replacing a specified element from a specified position.

<?php 
header("content-type:text/html;charset=utf-8");
$arr=array(1,2,3,4,5,6,7,8,9,10);
echo "原数组:";
var_dump($arr);
array_splice($arr,1,1,"hello");
echo "修改第2个元素:";
var_dump($arr);
?>

How to modify a value in an array in php

Recommended learning: "PHP Video Tutorial"

The above is the detailed content of How to modify a value in an array 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