PHP Arrays Ex. #1: Simple Array

Arrays allow you to assign multiple values to one variable. For this PHP exercise, write an array variable of weather conditions with the following values: rain, sunshine, clouds, hail, sleet, snow, wind. Using the array variable for all the weather conditions, echo the following statement to the browser:

We've seen all kinds of weather this month. At the beginning of the month, we had snow and wind. Then came sunshine with a few clouds and some rain. At least we didn't get any hail or sleet.

Don't forget to include a title for your page, both in the header and on the page itself.



Here's the script:

  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  2.      "">
  4. <html xmlns=""  xml:lang="en" lang="en">
  5. <head>
  6. <meta http-equiv="content-type" content="text/html;charset=iso-8859-1" />
  7. <title>Simple Array - Weather</title>
  8. </head>
  10. <body>
  11. <h2>How's the weather?</h2>
  13. <?php
  14. //Create array.
  15. $weather=array(
  16.   "rain",
  17.   "sunshine",
  18.   "clouds",
  19.   "hail",
  20.   "sleet",
  21.   "snow",
  22.   "wind" 
  23.   );
  25. //Use array in a sentence. 
  26. echo "<p>We've seen all kinds of weather this month. At the beginning of the month, ";
  27. echo "we had $weather[5] and $weather[6]. Then came $weather[1] with a few $weather[2] ";
  28. echo "and some $weather[0]. At least we didn't get any $weather[3] or $weather[4].</p>";
  29. ?>
  31. </body>
  32. </html>

See the output of the script in a separate window here. You can also view the output's HTML source from the new window, if you need to check that.



In a professional situation you would ideally separate the html from the php like this:

$arr = array("rain", "sunshine", "clouds", "hail", "sleet", "snow", "wind");

We've seen all kinds of weather this month. At the beginning of the month we had <?php echo $arr[5]; ?> and <?php echo $arr[6];?>. Then came <?php echo $arr[1]; ?> with a few <?php echo $arr[2]; ?> and some <?php echo $arr[0]; ?>. At least we didn't get any <?php echo $arr[3]; ?> or <?php echo $arr[4]; ?>.

Thanks for the insight. I find it interesting, however, that your example doesn't include any HTML tags at all. In a professional situation, especially striving for standards compliance, at least some <p> tags would be necessary.

In any case, either example works fine for the purpose of the exercise, which is to use the array to get at its values.

hello.. this is my first question so far for any other site like this. can you give me an idea how to sort value? what im doing is that when statement is true, it will add total.. so its on a loop everytime the system finds the statement is true it will come up with total. what i want is to sort the total out of that. thank you.. please help me..