Aims:
$extraToppings = array('mushrooms', 'anchovies', 'chocolate');
$extraToppings[0] = 'mushrooms';
$extraToppings[1] = 'anchovies';
$extraToppings[2] = 'chocolate';
$extraToppings[] = 'baked beans';
$extraToppings[1] = 'fried egg';
$firstTopping = $extraToppings[0];
echo "My favourite topping is: {$extraToppings[2]}";
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
<?php echo "<ul>"; foreach ($extraToppings as $topping) { echo "<li>{$topping}</li>"; } echo "</ul>"; ?>
$prices = array('Apples' => 1.59, 'Pears' => 2.34,
'Kumquats' => 4.05, 'Jujubes' => 2.34);
$prices['Apples'] = 1.59;
$prices['Pears'] = 2.34;
$prices['Kumquats'] = 4.05;
$prices['Jujubes'] = 2.34;
$prices['Mangoes'] = 5.26;
$prices['Kumquats'] = 3.93;
$priceOfPears = $prices['Pears'];
echo "The price of mangoes is: {$prices['Mangoes']}";
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
<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>
sort($a)
sorts array $a
into ascending order (use
rsort
for descending order)ksort($a)
sorts array $a
into ascending order
of its keys (or krsort
for descending order)asort($a)
sorts array $a
into asending order
of its values (or arsort
for descending order)array_keys($a)
returns an indexed array containing just the
keys of $a
array_values($a)
returns an indexed array containing just the
values of $a
$_SERVER
is a predefined associative array containing
lots of info from the web serverSERVER_SOFTWARE
HTTP_USER_AGENT
REQUEST_METHOD
GET
)
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>
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