Microsoft Word - Core PHP Programming Using PHP to Build Dynamic Web Sites

(singke) #1

array array_slice(array data, integer start, integer stop)


The array_slice function returns part of an array, starting with the element specified by
the start argument. If you specify a negative value for start, the starting position will
be that many elements before the last element. The optional stop argument allows you to
specify how many elements to return or where to stop returning values. A positive value
is treated as a maximum number of elements to return. A negative stop is used to count
backward from the last element to specify the element at which to stop.


Compare this function to array_merge and array_splice.


<?
function printElement($element)
{
print("$element
\n");
}


//set up an array of color names
$colors = array("red", "blue", "green",
"purple", "cyan", "yellow");


//get a new array consisting of a slice
//from "green" to "cyan"
$colors_slice = array_slice($colors, 2, 3);


//print out all the values
array_walk($colors_slice, "printElement");
?>


array_splice(array data, integer start, integer stop, array
insert_data)


The array_splice function removes part of an array and inserts another in its place. The
array passed is altered in place, not returned. Starting with the element specified by the
start argument, elements are removed until the element specified by the stop argument
is reached. If stop is left out, then removal continues until the end of the array. If stop is
negative, it references from the end of the array backward. It is possible to specify start
and stop values that do not actually remove any values. For instance, the stop value may
be positive and less than start. This is a valid way to use array_splice to insert an
array without removing any elements.


In place of any removed elements, the array passed as the insert_data argument is
inserted if it is supplied. Declaring it is optional, as you may wish simply to remove some
elements. If you wish to insert a single element into the array, you do not need to supply
an array for insert_data.

Free download pdf