How To Splice Using array_splice

Array_splice is very useful tool, it looks to me that is the only function you can use to insert an item in the middle of array.
The function is as this :


array_splice (  &$input , $offset , $length ,$replacement )

Do you feel it is bit hard to understand what the doc has said?

I would like to clarify it a bit and try to make it simpler and easier to understand

It is all about a spliced piece with its beginning decided by $offset, and the end or length of spliced decided by $length

$offset :this is not as hard as $length, if it is positive, count from beginning to end of array, first item offset is zero.

If it is negative, count from end to beginning of the array, first item offset is -1;

$length : it has different meanings when it is positive and negative.

When it is positive , this means the count of spliced items,
When it is negative, this means the last spliced item position from the end of array.
When it is zero then, it means no item is spliced, and replacement items will be pure insert.

A few points about this function:

1.It is confusing about the tip of $length from the doc:

To remove everything from offset to end use count($input)

Should not it be count($input)-$offset? I think the reason count($input) works is if you cut more items than it has then it won’t do any harm, but indeed is not very helpful for newbie to understand.

2.This only works with index based array, not associative arrays or arrays with key and value pairs

There are also a lot of examples given by commentators, but I would say you might not be able benefit from those scripts without any change. They have some limitations like not supporting append. But it is not hard to do this yourself.

The right approach as it has been pointed out in array_KSplice

$keys=array_Keys($input);
$values=array_Values($input);

To split your key and value pair array into two index based arrays($keys and $values), and you are free to splice in either split arrays, and then combine them back to one array

3.The replacement is array, even if there is only one item, please convert to an array before passing it to this function.

4.How to append items?

I was first in touch of this function because I have to insert an item, it is fine to insert in the middle using array_splice and set $length=0, but what if I have to append at the end of array? Funny thing is I cannot figure out how to append using array_splice($offset=-1,$length=-1 won’t solve this problem, as it inserts new item before the last item), but it turns out that $input[]= $newitem is the simplest way to add items to array. Back to square one!

This entry was posted on Friday, January 28th, 2011 at 3:00 am and is filed under PHP. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

Leave a Reply

*