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.

)<br />

[1] => 2<br />

[2] => 3<br />

)<br />

[1] => Array<br />

(<br />

[0] => 4<br />

[1] => 5<br />

[2] => 6<br />

)<br />

[2] => Array<br />

(<br />

[0] => 7<br />

)<br />

Keys and Values<br />

The array_keys( ) function returns an array consisting of only the keys in the array,<br />

in internal order:<br />

$array_of_keys = array_keys(array);<br />

Here’s an example:<br />

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

$keys = array_keys($person); // $keys is array('name', 'age', 'wife')<br />

<strong>PHP</strong> also provides a (less generally useful) function to retrieve an array of just the values<br />

in an array, array_values( ):<br />

$array_of_values = array_values(array);<br />

As with array_keys( ), the values are returned in the array’s internal order:<br />

$values = array_values($person); // $values is array('Fred', 35, 'Wilma');<br />

Checking Whether an Element Exists<br />

To see if an element exists in the array, use the array_key_exists( ) function:<br />

if (array_key_exists(key, array)) { ... }<br />

The function returns a Boolean value that indicates whether the second argument is<br />

a valid key in the array given as the first argument.<br />

It’s not sufficient to simply say:<br />

if ($person['name']) { ... } // this can be misleading<br />

Even if there is an element in the array with the key name, its corresponding value<br />

might be false (i.e., 0, NULL, or the empty string). Instead, use array_key_exists( ) as<br />

follows:<br />

$person['age'] = 0; // unborn?<br />

if ($person['age']) {<br />

122 | 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!