|
PHP Tutorial Home
Basic PHPPHP IntroductionPHP Installation PHP Syntax PHP Variables PHP Form Variables PHP If Statements PHP Switch Statements PHP Arrays PHP While Loops PHP For Loops PHP Operators PHP Functions Advanced PHPPHP IncludePHP Upload File PHP File PHP Mail PHP Database Driven Website PHP Summary Got a MySpace Page?Get "www.yourname.com" for your MySpace page. Learn how >>. |
PHP ArraysPHP arrays allow you to store groups of related data in one variable (as opposed to storing them in separate variables). Storing data like this in an array has many benefits. For example, if you have a lot of data, you could populate the array programmatically. You could also output the contents programatically - all you need to know if the name of the array. There are 3 different types of PHP arrays:
Numeric ArraysNumeric arrays use a number as the "key". The key is the unique identifier, or ID, of each item within the array. We can use this ID later when working with the contents within the array - we don't need to know the item's value, just the ID. Note that numbering starts at zero. Creating Numeric ArraysYou can choose between the following options when creating an array. Both of these options have the same result.
Displaying the Array ContentsYou can work with each value in an array by referring to its key. For example, to select the 2nd value in an array, we would do this: Example:
The above code results in:
Strawberries
Associative ArraysAssociative arrays are similar to numeric arrays but, instead of using a number for the key, we use a value. We then assign another value to the key - you could think of it as two values for the price of one! Creating Associative ArraysAs with creating numeric arrays, there are two options for creating associative arrays in PHP (although in both cases, we have to create the key manually).
Displaying the Array ContentsYou can display the contents of associative arrays just as you would with numeric arrays - by referring to it's key.
The above code results in the following:
Artichoke: 105 kilojoules
Multidimensional ArraysMultidimensional arrays allow you to put an array inside another array. In other words, the contents of the array is another array. You can do this as many times as you wish - you could have an array inside another array, which is inside another array, etc The following diagram demonstrates this. We have an array called "Food", which contains 3 arrays (called "Fruit", "Vegetables", "Grains"). Each of these arrays contain their own arrays (one for each food within that group).
Creating a Multidimensional ArrayWe can create the above array using the following code:
Enjoy this website?
Oh, and thank you for supporting Quackit! |
Featured Template:
(Build your websites in minutes!) |