Page 142 - Open Soource Technologies 304.indd
P. 142
Web Technologies-I
Notes
If the initial index is a non-numeric string, subsequent indexes are integers beginning at 0. Thus,
the following code is probably a mistake:
$whoops = array(‘Friday’ => ‘Black’, ‘Brown’, ‘Green’); // same as $whoops = array(‘Friday’
=> ‘Black’, 0 => ‘Brown’, 1 => ‘Green’);
6.3.1 Adding Values to the End of an Array
To insert more values into the end of an existing indexed array, use the [] syntax:
$family = array(‘Fred’, ‘Riya’); $family[] = ‘Pebbles’; // $family[2] is ‘Pebbles’
This construct assumes the array’s indexes are numbers and assigns elements into the next
available numeric index, starting from 0. Attempting to append to an associative array is almost
always a programmer mistake, but PHP will give the new elements numeric indexes without
issuing a warning:
$person = array(‘name’ => ‘Fred’); $person[] = ‘Riya’; // $person[0] is now ‘Riya’
6.3.2 Assigning a Range of Values
The range( ) function creates an array of consecutive integer or character values between the
two values you pass to it as arguments. For example:
$numbers = range(2, 5); // $numbers = array(2, 3, 4, 5); $letters = range(‘a’, ‘z’); // $numbers
holds the alphabet $reversed_numbers = range(5, 2); // $numbers = array(5, 4, 3, 2);
Only the first letter of a string argument is used to build the range:
range(‘aaa’, ‘zzz’) /// same as range(‘a’,’z’)
6.3.3 Getting the Size of an Array
The count( ) and sizeof( ) functions are identical in use and effect. They return the number of
elements in the array. There is no stylistic preference about which function you use. Here’s an
example:
$family = array(‘Fred’, ‘Riya’, ‘Pebbles’); $size = count($family); // $size is 3
These functions do not consult any numeric indexes that might be present:
$confusion = array( 10 => ‘ten’, 11 => ‘eleven’, 12 => ‘twelve’); $size = count($confusion); //
$size is 3
6.3.4 Padding an Array
To create an array initialized to the same value, use array_pad( ). The first argument to array_
pad() is the array, the second argument is the minimum number of elements you want the
array to have, and the third argument is the value to give any elements that are created. The
array_pad( )function returns a new padded array, leaving its argument array alone.
Here’s array_pad( ) in action:
$scores = array(5, 10); $padded = array_pad($scores, 5, 0); // $padded is now array(5, 10, 0, 0, 0)
Notice how the new values are appended to the end of the array. If you want the new values
added to the start of the array, use a negative second argument:
$padded = array_pad($scores, -5, 0);
Assign the results of array_pad( ) back to the original array to get the effect of an in situ change:
$scores = array_pad($scores, 5, 0);
136 LOVELY PROFESSIONAL UNIVERSITY