Cant understand array_splice(...) with 4 arguments?

Hi,
I am using 2 variations of array_splice(…) in the following code: one having 2 arguments and other having 4 arguments:

<?php 
$x = array(1, 2, 3, 4, 5); 
$x1 = array(9, 10, 11, 12); 
$x2 = array(60, 70, 80, 90); 

array_splice($x1, 0, 2, $x2); 
array_splice($x2, 2);

echo 'array $x1'."<BR>";
foreach ($x1 as $value) 
echo "$value"."<BR>"; 

echo 'array $x2'."<BR>";
foreach ($x2 as $value) 
echo "$value"."<BR>"; 
?>

I found that array_splice(…) is overloaded. I can understand
array_splice($x2, 2); i.e., array_splice with 2 arguments
but I can’t understand
array_splice($x1, 0, 2, $x2);

Somebody please explicitly state how array_splice($x1, 0, 2, $x2) i.e., with 4 arguments works ?
The output is:

array $x1
60
70
80
90
11
12
array $x2//This is fine, we will get only first 2 elements of $x2
60
70

Try changing some of the parameter values and notice the different results. Far mor satisfying to discover the solution.

1 Like

Did you read the PHP manual for array_splice? It is pretty self explanatory. It takes $x1, removes items starting at offset for length and puts in the replacement array ($x2). Simple example…

$a = [1,2,3,4,5];

// For $a, starting at index 1, remove 2 items and replace with ['a','b','c']
array_splice($a, 1, 2, ['a','b','c']);
var_dump($a);

From that comment, can you guess the result array? Simpler than you think. :slight_smile:

1 Like

Array_splice is describing a plumbing job. “Take the pipe” (input 1), “Cut it here” (input 2), “Take out this many inches” (input 3), “and put this in the hole you made.” (input 4)

1 Like

Hi,
I have the following program:

<?php
$O = array(1, 2, 3 , 4, 5); 
$new = array('$'); 
$O = array_splice ($O,2, 1,$new);
foreach ($O as $value)
   echo "$value" . "<BR>"
?>

I think it should work like:
// For $O, starting at index 2, remove 1 item and replace with [‘$’]
i.e. 1, 2, 3, $
but my answer is only 3,

Somebody please guide me.
Zulfi.

array_splice() operates on the input array, via a reference to that array. The return value is - Returns an array consisting of the extracted elements.

Remove the assignment - $O = part of that line of code.

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.