An array is a group of values that are placed in the same variable. These values can be of any type, and their data types can be mixed. You can also store other arrays inside an array. Another example of a PHP array is the days of the week. To create an array with the days of the week, review this example:
$week = array ("Mon","Tues","Wed","Thurs","Fri","Sat","Sun");
Our PHP array is named week. Notice that it looks similar to declaring a variable and assigning a variable other than the keyword “array”. Using the function array, we’re able to fill the array with the items in the parenthesis. Each item in a PHP array is called an element. Elements can be accessed by using an index number or key. The index number is the unique identifier of the element. The elements in the array are numbered starting from zero (0). So Tuesday would have an index number of 1, and Wed would be 2, etc… To access the value that is held in the PHP array we would use the following format:
That would print the forth element in the array, Thursday. By using the name of the array and then the index number in the square brackets to access the array element we are able to use the value held in the array element.
Another type of PHP array is an associative array. Associative arrays are much like regular arrays in PHP, but they use keys instead of index numbers. When declaring an associative array, we need to declare the keys and their values when declaring the array. For example:
$birthdays = array ( "name" => "Kris", "day" => "12", "month" => "1");
As you can see, an associative array is much like a regular array. The only difference being the assignment operator “=>”. By assigning the elements in the PHP array a key, we are able to access those elements by using the key and not the index number. For example:
This example would print “Kris” to the screen. If the array key uses a space in the name, you’ll need enclose the key with quotes (i.e. $birthdays[“my name”] ).
Arrays can be very useful when creating PHP scripts. The information they contain can vary and easily manipulated to use in your scripts. Using arrays in your PHP scripts can save time and clutter in your coding.