How to use array splice in PHP

In this article, I will explain how the array_splice() function can be used in PHP.
  • 1691

array_splice() function in PHP

  • The array_splice() function is used to removes selected elements from an array and replaces it with new elements.

  • The array_splice() function function also returns an array with the removed elements.

Syntax

array_splice(array,start,length,array)

Parameter

  • array  array is required parameter. Specifies an array.

  • start start is required parameter. start is the numeric value. Specifies where the function will start removing element.

  • length length is Optional parameter. length is the numeric value. determine how many elements will be removed, and also length of the returned array.

  • array array is Optional parameter. determine an array with the elements that will be inserted to the original array.

Example

The following example show to how the array_splice() function can be used in PHP.

<html>

<body>

<h3 style="color: seagreen;">array_splice() function example in PHP</h3>  

    <?php

    $a = array("Student", "Teacher", "Advocate", "Worker");

    array_splice($a, 2);

    print_r($a);

    print_r("<br />");

    $a1 = array("Student", "Teacher", "Advocate", "Worker");

    array_splice($a1, 1, -1);

    print_r($a1);

    print_r("<br />");

    $a2 = array("Student", "Teacher", "Advocate", "Worker");

    array_splice($a2, 1, count($a), "Nitin");

    print_r($a2);

    print_r("<br />");

    $a3 = array("Student", "Teacher", "Advocate", "Worker");

    array_splice($a3, -1, 1, array("Rajesh", "Manish"));

    print_r($a3);

    print_r("<br />");

    $a4 = array("Student", "Teacher", "Advocate", "Worker");

    array_splice($a4, 3, 0, "Ravi");

    print_r($a4);

    print_r("<br />");

    ?>

</body>

</html>

 

Output

splice.jpg

You may also want to read these related articles here
 
Ask Your Question 
 
Got a programming related question? You may want to post your question here
 

Categories

More Articles

© 2019 DotNetHeaven. All rights reserved.