To say that PHP uses arrays is a bit of a misstatement. Because PHP is a loosley typed language, it is designed to be easy for programmers, or web developers, to use. PHP arrays are not like arrays of most other languages, but in fact behave like sorted map. If you have used programming languages like C++ or Java, PHP arrays will seem very similar to maps, collections, and vectors. If not, then it doesn't matter.
The purpose of arrays is to store related data, like lists. It can be very difficult to remember individual variable names for each piece of data, and even harder to program it into PHP. Arrays make it very easy to organize this kind of data.
To initialize an array, simply type the following:
$variable = array();
And to put things into the array:
$variable[key] = value;
'key' in this case is the index, or the location of the data. The key can be either an integer or a string. Using an integer is useful when you need to cycle through many values or if you need to program the computer to enter data into the array. 'value' can be any valid PHP data type. To make arrays more useful, PHP includes several functions to manipulate arrays.
asort:
This function will sort all of the elements in the array by alphebetical order. While this might not have much impact on arrays that use numbers as keys, but if the key was a persons name, placing them in such an order can be very useful. To do so we simply use this syntax:
asort($variable);
next:
This function will find the first element in the array, return it, and then point to the next element in the array. So the next time you use the next command, it will return the second element, then the third, untill there are no more elements in the array in which case it will return false. The syntax for doing this is as follows
$stuff = next($array);
count:
This will count how many elements are stored in the array. The syntax is:
$number = count($array);
References: http://us2.php.net/
Contact Me | Policies | Colophon
© 2009, Jonathan Dunstan, All Rights Reserved.