Home and Learn: PHP Programming Course


Associative Array in PHP

 

Your arrays keys don't have to be numbers, as in the previous section. They can be text. This can help you remember what's in a key, or what it's supposed to do. When you use text for the keys, you're using an Associative array; when you use numbers for the keys, you're using a Scalar array. Here's an array that sets up first name and surname combinations:

$full_name = array( );

$full_name["David"] = "Gilmour";
$full_name["Nick"] = "Mason";
$full_name["Roger"] = "Waters";
$full_name["Richard"] = "Wright";

Fans of a certain band will know exactly who these people are! But look at the keys and values now:

David => "Gilmour",
Nick => "Mason",
Roger => "Waters",
Richard => "Wright"

This is easier to remember than this:

0 => "Gilmour",
1 => "Mason",
2 => "Waters",
3 => "Wright"

To access the values in an Associative array, just refer to the Key name:

print $full_name["David"];

However, because Associative arrays don't have numbers for the keys, another technique is used to loop round them – the For Each loop. We'll see how they work in the next part.

<-- Back One Page | Move on to the Next Part -->

Back to the PHP Contents Page

 

Email us: enquiry at homeandlearn.co.uk