Defining your own functions
Change the temperature example to use functions
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<!--
PHP two-dimensional arrays
Author: Elena Machkasova elenam@morris.umn.edu
Last modified: 3/3/08
-->
<?php
$data = array(array(2.8, 6.7, 4.5, 3.7, 5.0),
array(6.3, 7.8, 5.6, 8.0, 6.7, 7.9),
array(3.4, 5.2, 3.9, 4.6, 3.5));
$temperature = array("2/28/06" => array(24, 32, 41, 27),
"3/1/06" => array(25, 30, 37, 19),
"3/2/06" => array(15, 22, 26, 18));
?>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<title>
Two-dimensional arrays
</title>
<?php
// defining php functions
// the function prints a string as an h3 header
function pr_header($string) {
print "<h3>$string</h3>\n";
}
// the function computes and returns the average of
// elements of a one-dimensional array
function average($array) {
$sum = 0;
foreach ($array as $element) {
$sum = $sum + $element;
}
$average = $sum/count($array);
return $average;
}
// write a function that converts temperature from Fahrenheit to Celsius
// here is the formula: Tc = (Tf-32)*(5/9)
?>
</head>
<body>
<?php
pr_header("data");
print_r($data);
pr_header("temperature:");
print_r($temperature);
pr_header("Accessing an element in a 2D array:");
print $data[2][3]."<br/>\n";
print $temperature["3/1/06"][1]."<br/>\n";
// we use nested for loops here, we could use foreach instead (see below)
pr_header("Finding the average of each row of data");
for ($i = 0; $i < count($data); $i++) {
$average = average($data[$i]);
print "The average for row $i is $average<br/>\n";
}
pr_header("Finding the average of each row of temperature");
foreach ($temperature as $day => $temps) {
$average = average($temps);
// need brackets around $average, otherwise it's read as $averageF
print "The average temperature for $day is {$average}F<br/>\n";
}
?>
</body>
</html>
http://rynite.morris.umn.edu/~elenam/1101_spring08/functions/twod_array_functions.php
UMM CSci 1101