Home  >  Article  >  Backend Development  >  How to modify the contents of an array in php

How to modify the contents of an array in php

青灯夜游
青灯夜游Original
2022-04-29 20:48:223666browse

Method: 1. Use "array_values ​​(array)" to change the string key name to a numeric key name; 2. Use "array_replace (array 1, array 2)" to replace the array; 3. Use "array_splice(array, starting position, length, replacement value)" to delete, insert, and replace elements.

How to modify the contents of an array in php

The operating environment of this tutorial: Windows 7 system, PHP version 7.1, DELL G3 computer

php modification array Content method

1. Use array_values() function

array_values() is used to get the values ​​of all elements in the array

Use array_values() to change the string key name of the associative array into a numeric key name

<?php 
header("content-type:text/html;charset=utf-8");
$arr=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow");
var_dump($arr);
var_dump(array_values($arr));
?>

How to modify the contents of an array in php

2, array_replace() function

array_replace() function replaces the value of the first array with the value of the subsequent array.

<?php 
header("content-type:text/html;charset=utf-8");
$a1=array("red","green");
$a2=array("blue","yellow");
var_dump($a1);
var_dump(array_replace($a1,$a2));
?>

How to modify the contents of an array in php

3. Use array_splice() function

array_splice() is a powerful array function that can be set according to different parameters Implement operations of deleting elements, adding elements, and replacing elements.

Example 1: Delete element

<?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,2);
echo "从第2位开始删除2个元素:";
var_dump($arr);
?>

How to modify the contents of an array in php

Example 2: Replace element

<?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 the contents of an array in php

Example 3 : Insert element

<?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,0,"hello");
echo "在第1个元素后插入一个元素:";
var_dump($arr);
?>

How to modify the contents of an array in php

Recommended learning: "PHP Video Tutorial"

The above is the detailed content of How to modify the contents of 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