Array processing examples

 
Line 25: Line 25:
"Nov"=>30,"Dec"=>30);
"Nov"=>30,"Dec"=>30);
-
// Print the abbreviations of the months
+
// Print the indexes (0..11) of the months and the abbreviations
foreach($months as $key => $value) {
foreach($months as $key => $value) {
   print "$key -> $value<BR />";
   print "$key -> $value<BR />";
}
}
 +
echo "<br /><br />";
 +
// Print the abbreviations and the number of days of the month.
// Print the abbreviations and the number of days of the month.
Line 36: Line 38:
   print "$key -> $value<BR />";
   print "$key -> $value<BR />";
}
}
 +
echo "<br /><br />";
// Do the same thing another way
// Do the same thing another way
Line 42: Line 45:
   print "$value -> $monthsAndDays[$value]<BR />";
   print "$value -> $monthsAndDays[$value]<BR />";
}
}
 +
echo "<br /><br />";
// A function that computes the sum of the days in an associative array
// A function that computes the sum of the days in an associative array

Current revision as of 11:54, 15 March 2010

<?php
/*
 * Performs various operations on arrays
 *
 */
?>
<HTML>
  <HEAD>
    <TITLE>Arrays examples</TITLE>
  </HEAD>
  <BODY>
    <H4>Array Examples</h4>

<?php

//  Create an array for month abbreviations and an array that associates month
//  abbreviations with the number of days in the month.

$months = array('Jan', 'Feb', 'Mar', 'Apr', 'May', 
         'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec');

$monthsAndDays = array("Jan"=>31, "Feb"=>28,"Mar"=>31,"Apr"=>30,"May"=>31,"Jun"=>30,
         "Jul"=>31,"Aug"=>31,"Sep"=>30,"Oct"=>31,
"Nov"=>30,"Dec"=>30);

// Print the indexes (0..11) of the months and the abbreviations

foreach($months as $key => $value) {
   print "$key -> $value<BR />";
}
echo "<br /><br />";


// Print the abbreviations and the number of days of the month.

foreach($monthsAndDays as $key => $value) {
   print "$key -> $value<BR />";
}
echo "<br /><br />";

// Do the same thing another way

foreach($months as $key => $value) {
   print "$value -> $monthsAndDays[$value]<BR />";
}
echo "<br /><br />";

// A function that computes the sum of the days in an associative array
// Note that we can use any name we want for the parameter ($months), 
// including a name that has already been used in program.  This is
// because the parameter has local scope.

function sumDaysOfYear($months){
   $sum = 0;
   foreach ($months as $key => $value) {
       $sum += $value;
   }
   return $sum;
}

echo "There are " .  sumDaysOfYear($monthsAndDays) . " days in the year";

?>
  </BODY>
</HTML>