Wednesday, 24 September 2014

array_splice in PHP

array_splice() function is utilized to evacuate selected elements from an array and replace them with new elements. PHP array_splice() function also returns an array with the evacuated elements.

Syntax:

array_splice(array,start,length,array)

Parameters Description:
array : Required. Specifies an array
begin : Required. Numeric value. Details where the function will begin removing elements. 
0 = the first component. Assuming that this value is situated to a negative number, the function will begin that far from the last component. 
-2 methods begin at the second last component of the array.

length : Optional. Numeric value. Details what number of elements will be removed, and additionally length of the returned array. Provided that this quality is situated to a negative number, the function will prevent that far from the final component. Assuming that this value is not situated, the function will evacuate all elements, beginning from the position set by the start-parameter.

array : Optional. Determines an array with the elements that will be embedded to the original array. If it's only one element, it can be a string, and does not have to be an array.


Example:

<?php
$daysarr1 = array( 0=>"Sunday",1=>"Monday",2=>"Tuesday",3=>"Wednesday" );
$daysarr2 = array( 0=>"Thursday",1=>"Friday");
array_splice($daysarr1,0,2,$daysarr2)
print_r($daysarr1);
$daysarr1 = array( 0=>"Sunday",1=>"Monday",2=>"Tuesday",3=>"Wednesday" );
$daysarr2 = array( 0=>"Thursday",1=>"Friday");
echo "<br />"."output returned as array:";
print_r(array_splice($daysarr1,0,2,$daysarr2));
$daysarr1 = array( 0=>"Sunday",1=>"Monday" );
$daysarr2 = array( 0=>"Tuesday",1=>"Wednesday" );
echo "<br />"."using length parameter set to 0";
array_splice($daysarr1,1,0,$daysarr2);
print_r($daysarr1);
?>

Output:


Array (
          [0] => Thursday
          [1] => Friday
          [2] => Tuesday 
          [3] => Wednesday
        )
output returned as array:
Array (
          [0] => Sunday
          [1] => Monday
        )
using length parameter set to 0
Array ( 
         [0] => Sunday 
         [1] => Tuesday 
         [2] => Wednesday
         [3] => Monday
        )

0 comments:

Post a Comment