If

☰ Menu Content


Lets assume that you are going out to eat.
If you have enough money
Then you will eat at a restarunt
Otherwise you will eat at road side stall

This kind of simple if/then statement is very common in every day life.It also appears in programming quite very often.

The PHP If Statement

The if statement is very important in PHP.

An if statement is a way of controlling the execution of a statement that follows it.

The if statement evaluates an expression and if the results in a true, the statement is executed. Otherwise, the statement is skipped entirely.

This enables scripts to make decisions based on any number of factors.

If Statement Example
PHP Code:
$name = "Joe";

if ( $name == "Joe" ) {
echo "Your name is Joe!<br />";
}
echo "Welcome to my homepage!";
Display:
Your name is Joe!
Welcome to my homepage!

 Let's look at the details of this example.

  • We first set the variable "$name" equal to "Joe".
  • Next  a PHP statement was used to check if the value contained in the variable "$name" was equal to "Joe".
  • For comparison a double equal sign "==" was used, not a single equals"="! .
  • "$name" is indeed equal to "Joe" so the echo statement is executed.
A False If Statement

See what happens when a PHP if statement is not true,(false) 

PHP Code:
$name = "Sam";

if ( $name == "Joe" ) {
echo "Your name is Joe!<br />";
}
echo "Welcome to my homepage!";
Display:
Welcome to my homepage!

Here the variable contained the value "Sam", which is not equal to "Joe". 

The if statement evaluated to false, so the code segment of the if statement was not executed. 

When used properly, the if statement is very powerful.

Note
For more detail please see Php Manual at http://www.php.net

Php Tutorial Content (menu)