05.05.2013 Views

Programming PHP

Programming PHP

Programming PHP

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

The size of the replacement array doesn’t have to be the same as the number of elements<br />

you delete. The array grows or shrinks as needed:<br />

$new = array('law', 'business', 'IS');<br />

array_splice($subjects, 2, 4, $new);<br />

// $subjects is array('physics', 'chem', 'math', 'law', 'business', 'IS')<br />

To get the effect of inserting new elements into the array, delete zero elements:<br />

$subjects = array('physics', 'chem', 'math');<br />

$new = array('law', 'business');<br />

array_splice($subjects, 2, 0, $new);<br />

// $subjects is array('physics', 'chem', 'law', 'business', 'math')<br />

Although the examples so far have used an indexed array, array_splice( ) also works<br />

on associative arrays:<br />

$capitals = array('USA' => 'Washington',<br />

'Great Britain' => 'London',<br />

'New Zealand' => 'Wellington',<br />

'Australia' => 'Canberra',<br />

'Italy' => 'Rome');<br />

$down_under = array_splice($capitals, 2, 2); // remove New Zealand and Australia<br />

$france = array('France' => 'Paris');<br />

array_splice($capitals, 1, 0, $france); // insert France between USA and G.B.<br />

Converting Between Arrays and Variables<br />

<strong>PHP</strong> provides two functions, extract( ) and compact( ), that convert between arrays<br />

and variables. The names of the variables correspond to keys in the array, and the<br />

values of the variables become the values in the array. For instance, this array:<br />

$person = array('name' => 'Fred', 'age' => 35, 'wife' => 'Betty');<br />

can be converted to, or built from, these variables:<br />

$name = 'Fred';<br />

$age = 35;<br />

$wife = 'Betty';<br />

Creating Variables from an Array<br />

The extract( ) function automatically creates local variables from an array. The<br />

indexes of the array elements are the variable names:<br />

extract($person); // $name, $age, and $wife are now set<br />

If a variable created by the extraction has the same name as an existing one, the<br />

extracted variable overwrites the existing variable.<br />

You can modify extract( )’s behavior by passing a second argument. Appendix A<br />

describes the possible values for this second argument. The most useful value is<br />

124 | Chapter 5: Arrays<br />

This is the Title of the Book, eMatter Edition<br />

Copyright © 2002 O’Reilly & Associates, Inc. All rights reserved.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!