Information Technology News
Vamp the Linux LAMP through PHP part 2 | Vamp the Linux LAMP through PHP part 2 |
|
| by David M Williams | |
| Monday, 01 October 2007 | |
|
Page 2 of 3 Note that the array is indexed by a variable called $counter which begins at 0. That’s because, unless you specify otherwise, PHP will make arrays starting at index 0. This means we have to stop the loop before $counter is equal to the number 4 because the fourth element is actually at index 3.
Featured Whitepaper
5 Best Practices for Smartphone Support
$arr = array(1 => 10, 2 => 20, 3 => 30, 4 => 40);
We could go on for a long time: PHP is one of the most flexible and versatile programming languages which partially owes to its popularity (the fact that it is free and open source helps a lot too!) and offers no end of options to declaring and using arrays. To illustrate, here’s some more array code. All these lines are in sequence and are acting on the same array: The first line declares an array with four elements. The keys are not strictly numeric, nor are they strictly text strings. The key is “cat” for the first element, 2 for the second, “frog” for the third, and 55 for the fourth. You really can make any key you like, whether it is a number or a string and whether it is sequential or not – just so long as it is unique over the entire array. You’ll also see that $arr[“frog”] holds the value 30.3 this time just to illustrate that the array doesn’t care if all its values are the same type either. The one array can hold numeric values, string values or any other data type at any given position. It doesn’t matter what type of data is stored elsewhere. The second line adds another element to the array, with the value “Hello”. The catch this time is that there is no key (but there is an index value; there always will be.)
Finally, the third line adds another element to the array and gives it the key “more”. However, the value is not just a number or a string but another array, with six elements defined. You can print out the items in the array by using two sets of square brackets – so this line:
It might be worth thinking about all that for a moment. Arrays in PHP are hugely powerful owing to their remarkable flexibility.
|
| < Next story in category | Previous story in the category > |
|---|






