Sunday, March 15, 2009

PHP Arrays

Here are some of the useful facts and functions about arrays in PHP. Content of this post is summarized from Programming PHP by Kevin Tatroe and Rasmus Lerdorf. You can find the online version of this chapter here.

Indexed Vs Associative Arrays
PHP allows you to declare 2 kinds of array: Indexed and Associative. An indexed array means that the elements in the array are "indexed" or referred to by position in the array. To refer to the i-th element in the array, you simply call $arr[i-1](assuming $arr is the array name).

Elements in an associative array are key-value pairs. The keys are unique, so you cannot have two elements with the same key. An example of an associative array would be {'Gasket'=>15.29,'Wheel'=>75.25,'Tire'=>50.00}. To find out the "value" of Gasket, we use $arr['Gasket'].

Define Arrays

$addresses = array( );

Constructs an empty array

$addresses = array('spam@cyberpromo.net', 'abuse@example.com');

Initializes an indexed array

$price = array(
'Gasket' => 15.29,
'Wheel' => 75.25,
'Tire' => 50.00);

Initializes an associative array

Append Values to the End of Array
$family = array('Fred', 'Wilma');
$family[] = 'Pebbles'; // $family[2] is 'Pebbles'
Note that appending like this to an associative array might not yield the desired result.
$person = array('name' => 'Fred');
$person[] = 'Wilma'; // $person[0] is now 'Wilma'

Find Array Length
Use sizeof($arr)or count($arr). This works for both indexed and associative arrays.

Chapter 5 (Arrays) of the Programming PHP book offers an extensive range of array manipulation functions. You may want to check it out.

No comments:

Post a Comment