Aims:
count( $a )
(and sizeof) can be used on associative arrays as well as indexed arrays
array_key_exists( $k, $a )
returns true if $k is one of the keys in associative array $a,
otherwise returns false
isset( $variable ):if ( array_key_exists('Jujubes', $fruit_prices) ) ...if ( isset($fruit_prices['Jujubes']) ) ...$fruit_prices
contains a key/value pair where the key is 'Jujubes' and
the value is NULL
array_keys( $a )
returns an array containing just the keys in associative array $a
(usually in the order in which they were inserted)
array_values( $a )
returns an array containing just the values in associative array $a
(usually in the order in which they were inserted)
$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);
if ( array_key_exists( 'Mar', $month_lengths ) )
{
echo '<p>Beware the Ides of March</p>';
}
if ( isset($month_lengths['Mar']) )
{
echo '<p>The Ides of March are come</p>';
}
if ( array_key_exists( 'April', $month_lengths ) )
{
echo '<p>April is the cruelest month</p>';
}
if ( isset($month_lengths['April']) )
{
echo '<p>Drip, drip, drop, little April showers</p>';
}
$months = array_keys($month_lengths);
foreach ($months as $month)
{
echo "<p>{$month}</p>";
}
foreach (array_values($month_lengths) as $length)
{
echo "<p>{$length}</p>";
}
$module_lecturers array
as a table, one row per key/value (see left-hand table below)
echo "<table>";
foreach ($module_lecturers as $module => $lecturer)
{
echo "<tr>";
echo "<td>{$module}</td>";
echo "<td>{$lecturer}</td>";
echo "</tr>";
}
echo "</table>";
| AL1101 | Hugh Jeegoh |
| WC1101 | Ann O Domini |
| AL1101 | WC1101 |
| Hugh Jeegoh | Ann O Domini |
$_GET is an associative arrayform.html contains this form:
<form action="process.php" method="get">
<input type="text" name="firstname" />
<input type="text" name="surname" />
<input type="submit" />
</form>
GET process.php?firstname=Hugh&surname=Jeegoh
process.php, contains something like this to
access the user's data:
$firstname = $_GET['firstname']; $surname = $_GET['surname'];
$_GET$_ENV: the names and values of any environment variables$_GET: information submitted as a GET request$_POST: information submitted as a POST request$_COOKIE: names and values of any cookies passed as part of
a request
$_SERVER: information about the web server$_FILES: information about any uploaded files$_SERVER array contains many keys/values:HTTP_USER_AGENT, which gives the string the browser
used to identify itself
in_string( $s1, $s2 ),
which returns true if string s1 is contained within string
s2, and false otherwise (Surprisingly, there isn't such a
function that is exactly like this)