Pages

Your Ad Here

This Blog is not to read or go through

because, I have never been such a mess


Search the blog instead

Thursday, March 18, 2010

PHP array_splice vs. array_slice

Slice
array array_slice ( array $array , int $offset [,int $length [, bool $preserve_keys = false ]] )

Extract a slice of the array

Example :

$input= array("a", "b", "c", "d", "e");

$output = array_slice($input, 2); // returns "c", "d", and "e"
$output = array_slice($input, -2, 1); // returns "d"
$output = array_slice($input, 0, 3); // returns "a", "b", and "c"

// note the differences in the array keys
print_r(array_slice($input, 2, -1));
print_r(array_slice($input, 2, -1, true));





Splice
array array_splice ( array &$input , int $offset [, int $length = 0 [, mixed $replacement ]] )
Remove a portion of the array and replace it with something else

Example :

= 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, count($input), "orange");
// $input is now array("red", "orange")

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

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



Thanks - PHP.net

1 comment:

entertainmentgames09 said...

don't you have other examples? you just copy it on php.net

Your Ad Here