Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

PHP

Array_splice function

Can Anyone explain to me how array_splice function works ? I'm still confusing with this function.

1 Answer

array_splice — Remove a portion of the array and replace it with something else This function has 4 arguments: input - the array you want to splice, the offset - the key from where you want to remove. If your offset is 2(the array keys starts from 0 so 2 is the third not the second) that means it will start removing from the third element, the length - if the length is 4 and the offset is 2 it will remove starting from the third 4 elements. If the lenght is not specified it remove everything starting with the offset replacement - If replacement array is specified, then the removed elements are replaced with elements from this array.

$input = array("red", "green", "blue", "yellow");
array_splice($input, 2);
// $input is now array("red", "green")

$input = array("red", "green", "blue", "yellow");
array_splice($input, 1, -1);
// $input is now array("red", "yellow")

$input = array("red", "green", "blue", "yellow");
array_splice($input, -1, 1, array("black", "maroon"));

// $input is now array("red", "green", "blue", "black", "maroon")```