Home > Article > Backend Development > How to modify the contents of an array in php
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.
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)); ?>
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)); ?>
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); ?>
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); ?>
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); ?>
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!