The PHP Associative Array

The PHP Associative Array
In the previous tutorial, you learned that an array is a variable that stores several values or elements of data organized by index keys.

$books[0] = "Gone With The Wind";
$books[1] = "Little Women";
$books[2] = "War And Peach";

An associative array also uses index keys but these keys are not numeric as in the example above. The keys in an associative array are "named" keys which means that the keys are usually character strings. In the example below, you can see that the keys are words (title, name, organization) that have a meaning for the matching values (Professor, Mike Smith, Ohio State University).

$members = array(
"title" => "Professor",
"name" => "Mike Smith",
"organization" => "OSU"

The example above also demonstrates that you use the array function to create or initialize an associative array. The name of the array variable ($members) is followed by an equal sign and then the function name (array). Next you have the key-value pairs. Notice that these pairs are separated by commas. The key is "matched" to its value with the => and the whole group is enclosed in parenthesis. Last you have the semicolon. An associative array works much the same as a regular array.

  • You use the array square brackets to add a key-value pair to the array or to create an array.
    $members['tenured'] = "yes";

  • You use the key to reference an element in an associative array.
    echo "$members['name']";

This site needs an editor - click to learn more!

Editor's Picks Articles
Top Ten Articles
Previous Features
Site Map

Content copyright © 2023 by Diane Cipollo. All rights reserved.
This content was written by Diane Cipollo. If you wish to use this content in any manner, you need written permission. Contact BellaOnline Administration for details.