PHP tutorial - How to use if and else statement in PHP


How To Use If And Else Statement In PHP

If( )statement allows you to determine whether a condition is true or false. When it is true, the code within the if condition will be executed. If it is false, it will not be executed or will be executing the else( ) statement if provided.

To make it more simple, consider this statement. "If it's not raining, I will go and play football with my friends" . In this statement, I note that I'm going to play football with my friends if only it is not raining. But what happen when it rains? I will definetely won't go out or else I may get cold.

<?php

$todaysWeather = "raining";
if($todaysWeather == "raining") {
echo "I'm not going out";
}

?>

Take a look at the code above. The $todayWeather variable represents the weather condition today. Thus, when PHP read this code, it will check the if( ) statement to see whether it is true or false. If the condition is true, the code within the { ... }tags will be executed

Im not going out

So, what will PHP do when the condition returns false?
Good question! PHP will ignore those code within the if( ) statement when the condition is false and will just move to the next line. However, you can still use else( ) statement for PHP to execute when condition is false.

<?php

$todaysWeather = "raining";
if($todaysWeather == "raining") {
echo "Im not going out";
}
else {
echo "I will go and play football";
}

?>

In this case here, PHP will ignore the if( ) statement and execute the else( ) when it appears to be false!

I will go and play football

Try this Write me an application where it will display a statement saying 'Do not enter' when $myAge is under 18 and 'Welcome' when $myAge is above 18
  

Optimize Website - Webmasters optimize their site and gain higher search engine ranking

Webmaster tools - Free online webmaster toolkits, website reporting and free PHP opensource scripts.

Free Photo Hosting - Free File Hosting, Free ZIP file Hosting, Free Image Hosting, Free MP3 Hosting.

Funny Videos, Stupid Videos

Stupid Videos - Custom Pimped Motorcycle Pictures, Videos, and Articles

Planet Diaz - Programming Community - Online programming resource for programmers all around the world

Forectory - Webmaster Directory

St Louis Computer Networking

Website Templates - 1000s of Templates $5 - Many Templates to help you build your site!

 


Each and every tutorial published in PHPhelps.com is originally written by PHPHELPS OWNERS. None of the content is allowed to be replicated without prior notice to writter.
Copyright © 2006 PHPhelps.com