Page 119 - Open Soource Technologies 304.indd
P. 119
Open Source Technologies
Notes 7.8.2 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.
Example: <?php echo $val1[2]; ?>
7.8.3 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
[1] => 2
[2] => 3
)
Array
(
[0] => 1
[1] => 2
[2] => 3
)
So, you can see that you can use both the array() construct and the $arr[key] notation to create
arrays. Usually, array() is used to declare arrays whose elements are known at compile-time,
and the $arr[key] notation is used when the elements are only computed at runtime. PHP also
supports a special notation, $arr[], where the key is not specified. When creating new array
offsets using this notation (for example, using it as the l-value), the key is automatically assigned
as one more than the largest previous integer key.
114 LOVELY PROFESSIONAL UNIVERSITY