Here is our fruit example once again. Each item in an array is automatically assigned a number, or key. When working with arrays in PHP, numbering always starts with 0.
I am going to create the same array I have in the above example manually.
Get ready for this. Keys can be letters also. Let's scrap the fruit example for now. We're going to make a person array. This won't be an array of people, but an array of one person's attributes. I'll demonstrate creating this array using the 2 different methods I did with the fruit.
PHP Code:
// create the array all in one
$person = array(
'first_name' => 'John',
'last_name' => 'Smith',
'username' => 'jsmith'
);
// or create it one attribute at a time
$person['first_name'] = 'John';
$person['last_name'] = 'Smith';
$person['username'] = 'jsmith';
Now our $person variable contains the attributes of a person and we are using the key to specify the type of attribute.
Ready for a real-world example? In this example I'm going to query an imaginary database for all my users and return an array of people.
PHP Code:
function getPeople() {
// initialize people array
$people = array();
// query database ( assume i already have a connection )
$result = mysql_query("select first_name, last_name, username from users");
// iterate through results
while ($row = mysql_fetch_assoc($result)) {
// initialize a person array
$person = array();
$person['first_name'] = $row['first_name'];
$person['last_name'] = $row['last_name'];
$person['username'] = $row['username'];
// append people array
$people[] = $person;
}
return $people;
}
You can see how I'm getting the value from $row the same way I'm assigning it to $person. This is because mysql_fetch_assoc gets an array from the database. You could actually replace those 4 lines that begin with $person with $person = $row, but I wanted to demonstrate the long way for easier understanding.
Now look at the line below the comment: // append people array. We just created a $person array, and we are putting that into the $people array. This is called a Multi-Dimensional Array.
It's a pretty intimidating word, but doesn't what we just did make sense? I'll elaborate on the next page.