05.05.2013 Views

Programming PHP

Programming PHP

Programming PHP

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

echo "true!\n";<br />

}<br />

if (array_key_exists('age', $person)) {<br />

echo "exists!\n";<br />

}<br />

exists!<br />

In <strong>PHP</strong> 4.0.6 and earlier versions, the array_key_exists( ) function was called key_<br />

exists( ). The original name is still retained as an alias for the new name.<br />

Many people use the isset( ) function instead, which returns true if the element<br />

exists and is not NULL:<br />

$a = array(0,NULL,'');<br />

function tf($v) { return $v ? "T" : "F"; }<br />

for ($i=0; $i < 4; $i++) {<br />

printf("%d: %s %s\n", $i, tf(isset($a[$i])), tf(array_key_exists($i, $a)));<br />

}<br />

0: T T<br />

1: F T<br />

2: T T<br />

3: F F<br />

Removing and Inserting Elements in an Array<br />

The array_splice( ) function can remove or insert elements in an array:<br />

$removed = array_splice(array, start [, length [, replacement ] ]);<br />

We’ll look at array_splice( ) using this array:<br />

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

We can remove the math, bio, and cs elements by telling array_splice( ) to start at<br />

position 2 and remove 3 elements:<br />

$removed = array_splice($subjects, 2, 3);<br />

// $removed is array('math', 'bio', 'cs')<br />

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

If you omit the length, array_splice( ) removes to the end of the array:<br />

$removed = array_splice($subjects, 2);<br />

// $removed is array('math', 'bio', 'cs', 'drama', 'classics')<br />

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

If you simply want to delete the elements and you don’t care about their values, you<br />

don’t need to assign the results of array_splice( ):<br />

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

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

To insert elements where others were removed, use the fourth argument:<br />

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

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

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

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

Copyright © 2002 O’Reilly & Associates, Inc. All rights reserved.<br />

Extracting Multiple Values | 123

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

Saved successfully!

Ooh no, something went wrong!