Page 86 - Open Soource Technologies 304.indd
P. 86
Unit 6: Building Blocks of PHP
[2] => 3 Notes
)
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 (fo example, using it as the l-value), the key is automatically assigned
as one more than the largest previous integer key.
Therefore, the previous example can be rewritten as follows:
$arr1 = array(1, 2, 3);
$arr2[] = 1;
$arr2[] = 2;
$arr2[] = 3;
The result is the same as in the previous example.
The same holds true for arrays with string keys:
$arr1 = array(“name” => “John”, “age” => 28);
$arr2[“name”] = “John”;
$arr2[“age”] = 28;
if ($arr1 == $arr2) {
print ‘$arr1 and $arr2 are the same’ . “\n”;
}
The message confirming the equality of both arrays is printed.
Reading Array Values
You can use the $arr[key] notation to read array values. The next few examples build on top
of the previous example:
print $arr2[“name”];
if ($arr2[“age”] < 35) {
LOVELY PROFESSIONAL UNIVERSITY 81