# Array processing examples

 Revision as of 13:17, 19 September 2008 (view source)Sthayer (Talk | contribs)← Older edit Revision as of 11:48, 15 March 2010 (view source)Ram (Talk | contribs) Newer edit → Line 2: Line 2: - Arrays homework + Arrays examples -

Array homework

+

Array Examples

31, "Feb"=>28,"Mar"=>31,"Apr"=>30,"May"=>31,"Jun"=>30, \$monthsAndDays = array("Jan"=>31, "Feb"=>28,"Mar"=>31,"Apr"=>30,"May"=>31,"Jun"=>30, "Jul"=>31,"Aug"=>31,"Sep"=>30,"Oct"=>31, "Jul"=>31,"Aug"=>31,"Sep"=>30,"Oct"=>31, "Nov"=>30,"Dec"=>30); "Nov"=>30,"Dec"=>30); + + // Print the abbreviations of the months foreach(\$months as \$key => \$value) { foreach(\$months as \$key => \$value) { print "\$key -> \$value
"; print "\$key -> \$value
"; } } + + // Print the abbreviations and the number of days of the month. foreach(\$monthsAndDays as \$key => \$value) { foreach(\$monthsAndDays as \$key => \$value) { print "\$key -> \$value
"; print "\$key -> \$value
"; } } + + // Do the same thing another way foreach(\$months as \$key => \$value) { foreach(\$months as \$key => \$value) { print "\$value -> \$monthsAndDays[\$value]
"; print "\$value -> \$monthsAndDays[\$value]
"; } } + + // 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){ function sumDaysOfYear(\$months){

## Revision as of 11:48, 15 March 2010

```<?php
/*
* Performs various operations on arrays
*
*/
?>
<HTML>
<TITLE>Arrays examples</TITLE>
<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 abbreviations of the months

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

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

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

// Do the same thing another way

foreach(\$months as \$key => \$value) {
print "\$value -> \$monthsAndDays[\$value]<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>

```