PHP: Associative Arrays

Arrays in PHP are different from other programming languages like C/C++? Java that they allow heterogenous elements and support negative index. Associative arrays are like the hashmaps or the key value pairs. In case of associate arrays, the indices can be strings. They are called associative arrays because you associate a string to another value which can be of any type.

Let’s see a simple program. We associate different room numbers to the respective courses

<?php

$room['Room 101'] = "Physics";
$room['Room 102'] = "Chemistry";
$room['Room 103'] = "Biology";
$room['Room 104'] = "Computers";
$room['Room 105'] = "Languages";

foreach ($room as $key => $value) {
    echo "The $value course will be conducted in $keyn";
}
?>

Also notice the use of foreach which converts the associate array to key-value pairs
The output

The Physics course will be conducted in Room 101
The Chemistry course will be conducted in Room 102
The Biology course will be conducted in Room 103
The Computers course will be conducted in Room 104
The Languages course will be conducted in Room 105

You can consider the arrays with integer indices as key-value pairs

$days = array("Sunday", "Monday", "Tuesday", "Wednesday",
 "Thursday", "Friday", "Saturday");

foreach ($days as $key => $value) {
    echo "Day ", $key+1,"  : $valuen";
}

The output

Day 1  : Sunday
Day 2  : Monday
Day 3  : Tuesday
Day 4  : Wednesday
Day 5  : Thursday
Day 6  : Friday
Day 7  : Saturday
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s