Changes

Jump to: navigation, search

PHP Arrays

841 bytes added, 15:12, 1 June 2007
no edit summary
Once an array has been created items can be added, removed and modified, sorted and much more. The items in an arrasy can be of any variable type and an array can contain any mixture of data types - it is not necessary to have each element in the array of the same type.
Elements of an array are accessed using a key. There are two types of array depending on the type of key that is used to access an array element. In a numerical key array elements are accessed by specifying the numerical position of the item in the array. The first item in an array is element 0, the second is element 1 and so on. The second type of array is the ''associative array'' where a name is given to each element and that name is used to access the corresponding array element.
== Creating a PHP Array ==
 
Arrays are created using the ''array()'' function. ''array()'' function takes zero or more arguments and retruns the new array which must be assigned to a variable using the assigment operator. If arguments are provided they are used to initialize the array with data.
 
PHP arrays grow amd shrink dynamically as items are added and removed so it is not necessary to specify the array size at creation time as it is with some other programming languages.
 
We can create an empty array as follows:
 
<pre>
<?php
$colorArray = array();
?>
</pre>
 
Alternativelyt we can create an array pre-initialized with values by providing the values as arguments to the ''array()'' function:
 
<pre>
<?php
$colorArray = array("Red", "Yellow", "Green", "Blue", "Indigo");
?>
</pre>

Navigation menu