Page 85 - Open Soource Technologies 304.indd
P. 85
Open Source Technologies
Notes key even within the same declaration. The value itself can be of any PHP type, including an array.
Arrays containing arrays give a similar result as multi-dimensional arrays in other languages.
Here are a few examples:
array(1, 2, 3) is the same as the more explicit array(0 => 1, 1 => 2, 2 ‘=> 3).
array(“name” => “John”, “age” => 28)
array(1 => “ONE”, “TWO”, “THREE”) is equivalent to array(1 => “ONE”, 2 =>
→“TWO”, 3 => “THREE”).
array() an empty array.
Here’s an example of a nested array() statement:
array(array(“name” => “John”, “age” => 28), array(“name” =>
→“Barbara”, “age” => 67))
The previous example demonstrates an array with two elements: Each one is a collection (array)
of a person’s information.
Accessing Array Elements: Array elements can be accessed by using the $arr[key] notation,
where key is either an integer or string expression. When using a constant string for key, make
sure you don’t forget the single or double quotes, such as $arr[“key”]. This notation can be used
for both reading array elements and modifying or creating new elements.
Modifying/Creating Array Elements
$arr1 = array(1, 2, 3);
$arr2[0] = 1;
$arr2[1] = 2;
$arr2[2] = 3;
print_r($arr1);
print_r($arr2);
The print_r() function has not been covered yet in this book, but when it is passed an array, it
prints out the array’s contents in a readable way. You can use this function when debugging
your scripts.
The previous example prints
Array
(
[0] => 1
Gutmans_ch02 Page 24 Thursday, September 23, 2004 2:37 PM
[1] => 2
80 LOVELY PROFESSIONAL UNIVERSITY