Array Manipulation With PHP4 - Slice And Dice
(Page 5 of 8 )
PHP allows you to extract a subsection of the array with the array_slice() function, in much the same way that the substr() function allows you to extract a section of a string. Here's what it looks like:
array_slice(array, start, length)
where "array" is an array variable, "start" is the index to
begin slicing at, and "length" is the number of elements to return from "start".
Here's an example:
<?
// create array
$colours = array("red", "green", "blue", "yellow");
// returns the array ("green", "blue")
$slice = array_slice($colours, 1, 2);
?>
You can also use a negative index for the "start" position,
to force PHP to begin counting from the right instead of the left.
<?
// create array
$colours = array("red", "green", "blue", "yellow");
// returns the array ("green", "blue")
$slice = array_slice($colours, -3, 2);
?>
The array_splice() function allows you to splice one or more
values into an existing array. Here's what it looks like:
array_splice(array, start, length, replacement-values)
where "array" is an array variable, "start" is the index to
begin slicing at, "length" is the number of elements to return from "start", and "replacement-values" are the values to splice in.
Here's an example:
<?
// create array
$trio = array("huey", "dewey", "louie");
// section to be spliced in
$splice = array("larry", "curly", "moe");
// $trio now contains ("huey", "larry", "curly", "moe")
array_splice($trio, 1, 2, $splice);
?>
Next: Where Am I? >>
More PHP Articles
More By Vikram Vaswani, (c) Melonfire