Page 169 - Beginning PHP 5.3
P. 169
Chapter 6: Arrays
array_splice() lets you remove a range of elements in an array and replace them with the elements
from another array. Both the removal and the replacement are optional, meaning you can just remove
elements without adding new ones, or just insert new elements without removing any.
Here ’ s how it works. array_splice() takes the array to be manipulated, and the position of the first
element (counting from zero) to start the splice operation. (Remember that all arrays, even associative
arrays, have a concept of element positioning.) Next, you pass in an optional argument that specifies how
many elements to remove; if omitted, the function removes all elements from the start point to the end of
the array. Finally, you can pass another optional argument, which is the array of elements to insert.
array_splice() returns an array containing the extracted elements (if any).
Try It Out Playing with array_splice()
The following example script shows how to use the various parameters of array_splice(). Save it
as array_splice.php in your document root folder and open it in your Web browser. Figure 6-8
shows the result.
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Strict//EN”
“http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml” xml:lang=”en” lang=”en”>
<head>
<title>Using array_splice()</title>
<link rel=”stylesheet” type=”text/css” href=”common.css” />
<style type=”text/css”>
h2, pre { margin: 1px; }
table { margin: 0; border-collapse: collapse; width: 100%; }
th { text-align: left; }
th, td { text-align: left; padding: 4px; vertical-align: top; border:
1px solid gray; }
</style>
</head>
<body>
<h1>Using array_splice()</h1>
<?php
$headingStart = ‘<tr><th colspan=”4”><h2>’;
$headingEnd = ‘</h2></th></tr>’;
$rowStart = ‘<tr><td><pre>’;
$nextCell = ‘</pre></td><td><pre>’;
$rowEnd = ‘</pre></td></tr>’;
echo ‘<table cellpadding=”0” cellspacing=”0”><tr><th>Original
array</th><th>Removed</th><th>Added</th><th>New array</th></tr>’;
echo “{$headingStart}1. Adding two new elements to the middle{$headingEnd}”;
$authors = array( “Steinbeck”, “Kafka”, “Tolkien” );
$arrayToAdd = array( “Melville”, “Hardy” );
echo $rowStart;
131
9/21/09 9:00:20 AM
c06.indd 131
c06.indd 131 9/21/09 9:00:20 AM