PHP: Associative Arrays I

Derek Bridge

Department of Computer Science,
University College Cork

PHP: Associative Arrays I

Aims:

Associative arrays

Associative arrays

Accessing the elements in an associative array

Doing things to each value in an associative array

Class exercise: what is the output of the following?

echo "<table>";
foreach ($module_lecturers as $module => $lecturer) 
{
    echo "<tr>";
    echo "<td>{$module}</td>";
    echo "<td>{$lecturer}</td>";
    echo "</tr>";
}
echo "</table>";

Class exercise

Doing things to each value in an indexed and associative arrays

Class exercise

Hence, what does this output?

$toppings = array('mushrooms', 'anchovies', 'chocolate', 'baked beans');
echo "<ul>";
foreach ( $toppings as $k => $v )
{
    echo "<li>{$k}: {$v}</li>";
}
echo "</ul>";

And this?

$month_lengths = array('Jan' => 31, 'Feb' => 28, 
    'Mar' => 31, 'Apr' => 30, 'May' => 31, 'Jun' => 30, 'Jul' => 31,
    'Aug' => 31, 'Sep' => 30, 'Oct' => 31, 'Nov' => 31, 'Dec' => 31);
echo "<ul>";
foreach ( $month_lengths as $v )
{
    echo "<li>{$v}</li>";
}
echo "</ul>";