Arrays can be used in many ways to store and organize data quickly and efficiently. It is one of the more useful data types available to any programming language.
Arrays can most easily be described as an ordered list of elements. You can access the individual elements by referring to their index position within the array. The position is either specified numerically or by name. An array with a numeric index is commonly called an indexed array while one that has named positions is called an associative array. In PHP, all arrays are associative, but you can still use a numeric index to access them.
An Example of an indexed Array:
As you can see, elements in an array can be any type of data (string, integer, double) and can also be other variables. An individual array element can be of any type, including another array.If you want to find out if a variable contains an array you can use the is_array() function. Notice that Indexed arrays start at position zero, not at position one, so your first array element has an index of 0, and the highest position in the array is one less than the number of elements in the array.
Associative arrays are arrays that use named keys that you assign to them. Have a look at the following example:
Right, now you know how to define an associative array, but you probably don't see yet how useful are they. Well think of this, say you have a flower-shop. You have 3 different flowers, and each flower has a different price. Let's make this example in php.
Because the indices in this associative array are not numbers, we cannot use a simple counter in a for loop to work with the array. We can use the foreach loop. In the following example we use the foreach loop to iterate through our flowers_shop array, and read them into a table. Note carefully the syntax.
In preceding example you've learned how to use arrays. But what if you want to give more information on each flower? You now have the cost, but what if you wanted to add the number of flowers you get for that price, and the colour of the flower? One of the ways to do it is using multidimensional arrays.
A multidimensional array is an array that contains at least one other array as the value of one of the indexes. Example below shows how to use multidimensional array:
|Copyright © 2005-2007 www.WebCheatSheet.com All Rights Reserved.|