Page 141 - Open Soource Technologies 304.indd
P. 141
Unit 6: Arrays
You do not have to quote single-word strings. For instance, $age[‘Fred’] is the same as $age[Fred]. Notes
However, it is considered good PHP style to always use quotes, because quoteless keys are
indistinguishable from constants. When you use a constant as an unquoted index, PHP uses
the value of the constant as the index:
define(‘index’,5); echo $array[index]; // retrieves $array[5], not $array[‘index’];
You must use quotes if you are using interpolation to build the array index:
$age[“Clone$number”]
However, do not quote the key if you are interpolating an array lookup:
// these are wrong print “Hello, $person[‘name’]”; print “Hello, $person[“name”]”; // this is
right print “Hello, $person[name]”;
Develop a program for finding element of array.
6.3 Storing Data in Arrays
Storing a value in an array will create the array if it did not already exist, but trying to retrieve
a value from an array that has not been defined yet would not create the array. For example:
// $addresses not defined before this point echo $addresses[0]; // prints nothing echo $addresses;
// prints nothing $addresses[0] = ‘spam@cyberpromo.net’; echo $addresses; // prints “Array”
Using simple assignment to initialize an array in your program leads to code like this:
$addresses[0] = ‘spam@cyberpromo.net’; $addresses[1] = ‘abuse@example.com’; $addresses[2]
= ‘root@example.com’; // ...
That’s an indexed array, with integer indexes beginning at 0. Here’s an associative array:
$price[‘Gasket’] = 15.29; $price[‘Wheel’] = 75.25; $price[‘Tire’] = 50.00; // ...
An easier way to initialize an array is to use the array( ) construct, which builds an array from
its arguments:
$addresses = array(‘spam@cyberpromo.net’, ‘abuse@example.com’, ‘root@example.com’);
To create an associative array with array( ), use the => symbol to separate indexes from values:
$price = array(‘Gasket’ => 15.29, ‘Wheel’ => 75.25, ‘Tire’ => 50.00);
Notice the use of whitespace and alignment. We could have bunched up the code, but it would
not have been as easy to read:
$price = array(‘Gasket’=>15.29,’Wheel’=>75.25,’Tire’=>50.00);
To construct an empty array, pass no arguments to array( ):
$addresses = array( );
You can specify an initial key with => and then a list of values. The values are inserted into the
array starting with that key, with subsequent values having sequential keys:
$days = array(1 => ‘Monday’, ‘Tuesday’, ‘Wednesday’, ‘Thursday’, ‘Friday’, ‘Saturday’, ‘Sunday’);
// 2 is Tuesday, 3 is Wednesday, etc.
LOVELY PROFESSIONAL UNIVERSITY 135