Saturday, 15 December 2012

PHP If Else Statement

PHP If.... Else Statement

Sometimes when you write code, you want to perform different actions for different decisions. You can use conditional statement If Else in your code to do this. Conditional statements are the set of commands used to perform different actions based on different conditions. In this tutorial we will look at if...else statement.

The If Statement is a way to make decisions based upon the result of a condition. For example, you might have a script that checks if boolean value is true or false, if variable contains number or string value, if an object is empty or populated, etc. The condition can be anything you choose, and you can combine conditions together to make for actions that are more complicated.

Use the if statement to execute a statement if a logical condition is true. Use the optional else clause to execute a statement if the condition is false. The syntax for If statement looks as follows:

if (condition) {
    statements_1
} else {
    statements_2
}

Condition can be any expression that evaluates to true or false. If condition evaluates to true, statements_1 are executed; otherwise, statements_2 are executed. statement_1 and statement_2 can be any statement, including further nested if statements.

You may also compound the statements using elseif to have multiple conditions tested in sequence. You should use this construction if you want to select one of many sets of lines to execute.

if (condition_1) {
    statement_1
}[elseif (condition_2) {
    statement_2
}][else {
    statement_n
}]

Let's have a look at the examples. The first example decides whether a student has passed an exam with a pass mark of 40:

<?php
$result = 68;
if ($result >= 40) {
    echo "Pass <br />";
} else {
    echo "Fail <br />";
}
?>

0 comments:

Post a Comment