array_splice() can remove a range of elements in an array and replace them with the elements from another array.
Both the removal and the replacement are optional, meaning you can just remove elements without adding new ones, or just insert new elements without removing any.
array_splice() takes
Next, you pass in an optional argument that specifies how many elements to remove.
If omitted, the function removes all elements from the start point to the end of the array.
Finally, you can pass another optional argument, which is the array of elements to insert.
array_splice() returns an array containing the extracted elements (if any).
The following example script shows how to use the various parameters of array_splice().
Adding two new elements to the middle
<?php $authors = array("A","B","C"); $arrayToAdd = array("M","Hardy"); echo $rowStart;/*from ww w. jav a2 s .c o m*/ print_r($authors); echo $nextCell; print_r(array_splice($authors, 2, 0, $arrayToAdd)); echo $nextCell; print_r($arrayToAdd); echo $nextCell; print_r($authors); echo $rowEnd; ?>
Replacing two elements with a new element{$headingEnd}
<?php $authors = array("A","B","C"); $arrayToAdd = array("Bronte"); echo $rowStart;//from w w w . j av a 2s . c o m print_r($authors); echo $nextCell; print_r(array_splice($authors, 0, 2, $arrayToAdd)); echo $nextCell; print_r($arrayToAdd); echo $nextCell; print_r($authors); echo $rowEnd; ?>
Removing the last two elements{$headingEnd}
<?php $authors = array("A","B","C"); echo $rowStart;/* ww w .j a v a2s . c o m*/ print_r($authors); echo $nextCell; print_r(array_splice($authors, 1)); echo $nextCell; echo"Nothing"; echo $nextCell; print_r($authors); echo $rowEnd; ?>
Inserting a string instead of an array{$headingEnd}
<?php $authors = array("A","B","C"); echo $rowStart;/*from w ww.j a v a2 s . c om*/ print_r($authors); echo $nextCell; print_r(array_splice($authors, 1, 0,"O")); echo $nextCell; echo"O"; echo $nextCell; print_r($authors); echo $rowEnd; echo'</table>'; ?>