PHP: Arrays

Derek Bridge

Department of Computer Science,
University College Cork

PHP: Arrays

Aims:

Indexed arrays

Doing things to indexed arrays

Doing things to each value in an indexed array

foreach ($a as $v)
{
  ...do something to $v...
}

This is a loop which visits each value in array $a in turn, referring to them as $v

You may have any number of statements within the braces

Doing things to each value in an indexed array

<?php
 echo "<ul>";
 foreach ($extraToppings as $topping) 
 {
   echo "<li>{$topping}</li>";
 }
 echo "</ul>"; 
?>

Associative arrays

Doing things to associative arrays

Doing things to each value in an associative array

foreach ($a as $k => $v)
{
  ...do something to $k and/or $v...
}

This is a loop which visits each key and value in array $a in turn, referring to them as $k and $v

You may have any number of statements within the braces

Doing things to each value in an associative array

<table>
 <tr><th>Fruit</th><th>Price</th></tr>
<?php
  foreach ($prices as $fruit => $price) 
  {
    echo "<tr>
           <td>{$fruit}</td>
           <td>{$price}</td>
         </tr>";
  }
?>
</table>

PHP's 84+ built-in functions for arrays

One of PHP's predefined associative arrays

One of PHP's predefined associative arrays

It's easy to output the contents of the $_SERVER array as a table, one row per key/value

<table>
<?php
  foreach ($_SERVER as $variable => $value) 
  {
    echo "<tr>
           <th>{$variable}:</th>
           <td>{$value}</td>
         </tr>";
  }
?>
</table>

Class exercise

Write a PHP script that outputs the contents of the $_SERVER array as a table, but this time let's have one column per key/value