In PHP, you can use the array_splice() function to add elements to the middle of the array. You only need to set the second parameter of the function to a value greater than 0 and less than "array length -1". Syntax "array_splice(array, index position to be inserted, 0, element value)".
The operating environment of this tutorial: windows7 system, PHP7.1 version, DELL G3 computer
php is in the middle of the array Add elements
In PHP, you can use the array_splice() function to add elements in the middle of the array.
array_splice($array,$start,$length,$value)
The function can insert new elements into any position of the array.
When $length=0, then the parameter $start can specify the position (subscript) to start inserting, and the parameter $value can specify the insertion value (if there are multiple values, it needs to be set as an array).
Example:
<?php header("Content-type:text/html;charset=utf-8"); $arr1=array(10,12,20); array_splice($arr1,0,0,"1"); var_dump($arr1); $arr1=array(10,12,20); array_splice($arr1,1,0,"1"); var_dump($arr1); $arr2=array(10,12,20); array_splice($arr2,2,0,array("1",25,"3")); var_dump($arr2); ?>
It can be seen that when the value of parameter $start is greater than 0 and less than "array length-1", it can be in the middle of the array Add elements.
Recommended learning: "PHP Video Tutorial"
The above is the detailed content of How to add elements in the middle of array in php. For more information, please follow other related articles on the PHP Chinese website!