1. Home
  2. Computing & Technology
  3. PHP / MySQL

Learn PHP - A Beginner's Guide to PHP Programing

By Angela Bradley, About.com

8 of 9

Conditional Statements

Conditionals allow your program to make choices. Following the same sort of boolean logic you just learned about, the computer can only make two choices; true or false. In the case of PHP this is accomplished using IF : ELSE statements. Below is an example of an IF statement that would apply a senior's discount. If $over65 is false, everything within the {brackets} is simply ignored.

<?php
$over65 = true;
$price = 1.00;
if ( $over65 )
{
$price = .90;
}
print "Your price is $" . $price;
?>

However, sometimes just the IF statement isn't enough, you need the ELSE statement as well. When using just the IF statement the code within the brackets either will (true) or will not (false) be executed before carrying on with the rest of the program. When we add in the ELSE statement, if the statement is true it will execute the first set of code and if it is false it will execute the second (ELSE) set of code. Here is an example:

<?php
$over65=true;
$price = 3.00;
if ($over65)
{
$discount =.90;
print "You have received our senior's discount, your price is $" . $price*$discount;
}
else
{
print "Sorry you do not qualify for a discount, your price is $" . $price;
}
?>

Index: Learn PHP - A Beginner's Guide to PHP Programing

  1. Basic PHP Syntax
  2. Comments
  3. PRINT and ECHO Statements
  4. Variables
  5. Arrays
  6. Operands
  7. Operators
  8. Conditional Statements
  9. Nested Conditionals

8 of 9

Explore PHP / MySQL

More from About.com

  1. Home
  2. Computing & Technology
  3. PHP / MySQL
  4. PHP Functions
  5. Learn PHP - PHP Tutorial - Conditional Statements

©2008 About.com, a part of The New York Times Company.

All rights reserved.