Learn PHP-21 : if… else… else if Statements

Posted: November 20, 2010 in PHP
Tags:

We use the if… else… else if statements to establish conditional logic and evaluate things when needed in our scripts. Sometimes you have to evaluate values to then give the user the correct output on page once the variable value is checked.

if

<?php $current_temperature = 37; // Current South Pole temperature // Then the if statement will evaluate it for us if ($current_temperature > 32) { // Set things to melt if the temp is exceeding 32(freezing) echo "Doom! The icecaps will melt, sea levels will rise."; } // If the temp is still freezing(32), nothing at all will happen in this script ?>
 

The browser is shown like below

Doom! The icecaps will melt, sea levels will rise.

else

<?php $current_temperature = 30; // Current South Pole temperature if ($current_temperature > 32) { echo "Doom! The icecaps melt, sea levels rise."; } else { echo "The temperature is below freezing, everything is stable in the south pole."; } ?>
 

The browser is shown like below

The temperature is below freezing, everything is stable in the south pole.

else if allows us to keep evaluating using if statements as many times as needed.

else if

<?php $cur_temp = 28; // Current South Pole temperature if ($cur_temp > 32) { // If temp is greater than 32 degrees F echo "The icecaps melt, sea levels rise."; } else if ($cur_temp < -45) { // If temp is less than -45 degrees F echo "Mammals that live on surface start to die, it is too cold for them to live."; } else if ($cur_temp < -250) {  // If temp is less than -250 degrees F echo "The entire planet freezes over on the crust, all life on top dies."; } else { // default last clause, can be removed if needed echo "Everything is great, and earth conditions are fine for a good balance."; } ?>

The browser is shown like below

Everything is great, and earth conditions are fine for a good balance.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s