PHP - Adding and Removing Elements in the Middle

Introduction

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

  • the array to be manipulated, and
  • the position of the first element counting from zero to start the splice operation.

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

Demo

<?php
        $authors = array("A","B","C");
        $arrayToAdd = array("M","Hardy");
        echo $rowStart;//from   w w w .  j  a v  a  2 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;

?>

Result

Replacing two elements with a new element{$headingEnd}

Demo

<?php

      $authors = array("A","B","C");
      $arrayToAdd = array("Bronte");
      echo $rowStart;/*from   w w  w.  ja v  a  2 s .  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;


?>

Result

Removing the last two elements{$headingEnd}

Demo

<?php
      $authors = array("A","B","C");
      echo $rowStart;//from   w  ww.ja va 2  s. 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;
?>

Result

Inserting a string instead of an array{$headingEnd}

Demo

<?php


      $authors = array("A","B","C");
      echo $rowStart;/*  ww w. java  2s . co  m*/
      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>';

?>

Result

Related Topic