Replacement method: 1. Use "array_replace (array, replace array)" to replace the elements of the first array with the elements of the subsequent array. 2. Use "array_splice(array, starting position, number, replacement value)" to replace the specified number of elements starting from the specified position. If multiple values are replaced, the replacement value can be an array.
The operating environment of this tutorial: windows7 system, PHP7.1 version, DELL G3 computer
PHP replacement array Two methods for elements:
1. Use array_replace() function
array_replace() function uses the value of the following array to replace the first one The value of the array.
array_replace(数组,替换数组)
Note: There can be multiple replacement arrays, separated by ,
.
<?php $a1=array(1,2,3,4,5); $a2=array("blue","yellow"); $a3=array("a","b","c","d","e","f"); var_dump(array_replace($a1,$a2)); var_dump(array_replace($a1,$a3)); ?>
If you specify multiple arrays to be replaced, the values of the subsequent arrays will overwrite the values of the previous arrays.
<?php $a1=array(1,2,3,4,5); $a2=array("blue","yellow"); $a3=array("a","b","c","d","e","f"); var_dump(array_replace($a1,$a3,$a2)); var_dump(array_replace($a1,$a2,$a3)); ?>
2. Use array_splice() function
array_splice() is a powerful function that can realize deletion, insertion, Replace element operation.
array_splice($array,$start,$length,$replacement)
Parameters:
If a replacement operation is performed, the length value and the number of replacements need to be consistent.
Note that using replacement to replace array elements will not retain the original key names.
<?php header('content-type:text/html;charset=utf-8'); $arr=array(1,2,3,4,5); var_dump($arr); array_splice($arr,1,1,"H"); var_dump($arr); array_splice($arr,1,3,array("a","b","c")); var_dump($arr); ?>
Recommended learning: "PHP Video Tutorial"
The above is the detailed content of How to replace elements in an array in PHP. For more information, please follow other related articles on the PHP Chinese website!