Home>Article>Backend Development> PHP array inserts elements at any position and deletes instance details of specific elements
The following editor will bring you an example of inserting elements at any position in an array and deleting specific elements. The editor thinks it is quite good, so I will share it with you now and give it as a reference for everyone. Let’s follow the editor and take a look.
is as follows:
$ary = array( array('t'=>1,'y'=>2), array('t'=>2,'y'=>9) ); $t = array_splice( $ary, 1,0,array(array('t'=>3,'y'=>10)) ); print_r($ary);
Control Station output:
$ary = array( array('t'=>1,'y'=>2), array('t'=>3,'y'=>10), array('t'=>2,'y'=>9) );
Briefly introduce the array_splice method. The first parameter is the array being operated on, the second parameter is the index value of the operating element, and the third parameter is is the length, parameter four is the element to be replaced. The effect of this method is to delete the consecutive elements in the parameter array with parameter two as the starting position and length parameter three, and then fill them with parameter four.
If the length is 0, the effect is equivalent to inserting the specified element at the specified index value.
If the length is 1, the effect is equivalent to removing the element with the index value
$ary = array( array('t'=>1,'y'=>2), );
Deleting specific elements in the array
$arr1 = array(1,3, 5,7,8); $key = array_search(3, $arr1); if ($key !== false){ array_splice($arr1, $key, 1); } var_dump($arr1);
Output: array(1, 5,7,8);
array_slice(array,start,length,preserve)
From the array The start element starts to be taken out and the remaining elements in the array are returned
$a=array("red","green","blue","yellow","brown"); print_r(array_slice($a,2));
Output array("blue","yellow","brown")
array_push
array_push -- Push one or more cells to the end of the array (push)
Description
int array_push ( array &array, mixed var [, mixed ...] )
array_push() treats array as a stack and pushes the passed variable into the end of array. The length of array will increase according to the number of variables pushed onto the stack.
The above is the instance details of inserting elements at any position in the array and deleting specific elements. For more related content, please pay attention to the PHP Chinese website (m.sbmmt.com)!