#native_company# #native_desc#
#native_cta#

Introduction to Arrays and Hashes in PHP Page 2

By PHP Builder Staff
on April 29, 2009

What’s the deal with starting at 0?
Honestly? I really don’t know, I’m guessing it’s because of PHP’s similarity to the C programming language, and traditionally all versions of C and C++ start array indexes at 0, it may also be to do with the way loops work, all I know is that if the PHP function “count()” returns a number other than 0, then your highest index is that number minus 1.
Arrays don’t always have to hold the same types
Just because an array is set up as a ‘shopping list’ or ‘age list’ it does not mean that you have to always put that type of data in it, you can freely mix and match data types and PHP will adapt automatically, eg:


$myArray = array();
$myArray[] = "Peter";
$myArray[] = "Shaw";
$myArray[] = 21;

As you can see I’ve added 2 text strings and 1 number (Which I wish was my age again : )
This shows that you could, in actual fact, store a complete record of mixed information in memory, the system is so flexible that you can even store an array, eg:


$myArray = array();
$myArray[] = "Peter";
$myArray[] = "Shaw";
$myArray[] = 21;
$myArray[] = array("Computers","Programming","Electronics");

If you use “print_r” to display this, you’ll get the following:
Array
(
    [0] => "Peter"
    [1] => "Shaw"
    [2] => 21
    [3] => Array
      	  (
            	[0] => "Computers"
            [1] => "Programming"
            [2] => "Electronics"
      	  )

)
print_r is a fantastic function for debugging, because it displays the array structure and it’s contents in a nice neat tree diagram, if you are using print_r in a web page though, you will want to print an opening and closing pre tags (<pre> </pre>) on either side of it to preserve the layout.
Nested arrays are great for representing complex data, unfortunately you still need to remember your indexes and the deeper you go the more complex this becomes, how do you remember that “$myArray[0][3][2][1]” is equal to the first name of the second cousin in the third family of the family tree? That’s solved by the one thing we’ve not covered yet and that’s hashes.