#native_company# #native_desc#
#native_cta#

Introduction to Arrays and Hashes in PHP Page 3

By PHP Builder Staff
on April 29, 2009

Array elements have names
A hash is pretty much a mixed format array, the major difference is that names are used rather than index numbers. Taking the example above we could now write the following:


$myHash = array();
$myHash['firstname'] = "Peter";
$myHash['lastname'] = "Shaw";
$myHash['age'] = 21;
$myHash['hobbies'] = array(0 => "Computers", 1 =>
"Programming", 2 => "Electronics");

We then print_r it:


Array
(
  [firstname] => Peter
  [lastname] => Shaw
  [age] => 21
  [hobbies] => Array
  (
    [0] => Computers
    [1] => Programming
    [2] => Electronics
  )
  )

You can see straight away how much more descriptive it is, so I can now do things like:


Print "First name is : " . $myArray['firstname'];

Which will result in this being displayed:


"First name is : Peter"

I can also show a hobby by using it:


Print "First hobby is : " . $myArray['hobbies'][0];

You should also see that in the second array we now create the indexes using the arrow syntax:


0 => "Computers";

This is telling PHP to use 0 as the index, we could just as easily used:


"Hobby0" => "Computers"

By using the arrow syntax we can define not only the contents of a hash at creation time, but the names the elements use in a nice neat easy to read way.
I’ll show you how to loop over the elements next time when we cover loops and decisions, but for now we’ll leave it there.
In Summary
Today we learned how to represent our data in memory using complex collections to keep our data organized. Once you start using databases you’ll quickly realize that using these techniques to model your tables in memory will greatly assist you with display and management of your data in web pages, hashes are also a large part of object orientated programming and allow you to keep a tight hold of your class related data when using that programming model. I’m not going to cover class programming in this series however because that is quite a complex subject.
As always, I encourage you to look at the PHP Manual, and explore the functions available for working with arrays and hashes, the section to read can be found at http://www.php.net/manual/en/book.array.php so until next time.
Happy hashing.
Shawty