Created
March 5, 2014 00:31
-
-
Save robynitp/9358844 to your computer and use it in GitHub Desktop.
Example PHP logic using a simple weather app
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE HTML> | |
<html> | |
<head> | |
<title>The colors of weather</title> | |
<?php | |
$temp = 45; | |
$conditions = 'rain'; | |
/* | |
color the background based on the weather conditions, | |
as follows: | |
snow = white | |
rain = green | |
clear = blue | |
sunny = yellow | |
cloudy = gray | |
*/ | |
$colors = array( | |
'snow' => 'white', | |
'rain' => 'green', | |
'clear' => 'blue', | |
'sunny' => 'yellow', | |
'cloudy' => 'gray', | |
); | |
$background_color = $colors[$conditions]; //blue | |
/* | |
Make the background color a CSS style for the body | |
Break out of PHP to throw that in. | |
Then we break back into PHP for a sec to output the color. | |
*/ | |
?> | |
<style type="text/css"> | |
body{ | |
background-color: <?php echo $background_color; ?> | |
} | |
</style> | |
</head> | |
<body> | |
<?php | |
// now we're back in PHP | |
/* | |
Show a photo based on the temperature | |
0 - 20 : icicles.jpg | |
21 - 40 : ski mask.jpg | |
41 - 60 : jogging.jpg | |
61 - 80 : picnic.jpg | |
81 - 100 : swimming.jpg | |
*/ | |
$photos = array( | |
'icicles.jpg', | |
'ski.jpg', | |
'jogging.jpg', | |
'picnic.jpg', | |
'swimming.jpg' | |
); | |
$image = false; // false because we don't have an image yet | |
// loop through the photos until we find the one that corresponds to the temperature | |
foreach ($photos as $key=>$image_name){ | |
$num = $key + 1; | |
$low = $num * 1; | |
$high = $num * 20; | |
if ($temp >= $low && $temp <= $high){ | |
$image = $image_name; | |
// Found it! We can leave the loop now. | |
break; | |
} | |
} | |
// put the photo in an <img> tag | |
echo '<img src="' . $image . '"/>'; | |
// tip: if you REALLY want to see this in its full glory, make some jpgs and name them icicles.jpg, ski.jpg, etc | |
?> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment