PHP Control Statement(if, if-else, else-if) With Example

aimtocode

PHP Control Statements

The control statements are divided into decision making statemennt and looping statements.

This means, you can create test conditions in the form of expressions that evaluates to either true or false and based on these results you can perform certain actions.

  • if-statement executes some code only if a specified condition is true.
  • if...else-statement some code if a condition is true and another code if the condition is false.
  • if...elseif..else-statement specifies a new condition to test, if the first condition is false.
  • switch statement- selects one of many blocks of code to be executed.

if Statement

This statement is used for testing a condition and excuting a part of code based on the result of the condition.
The condition shuld be a boolean expression which evaluates to either true or false.
if(expression or condition)
}
..................
Statement;
}

The condition or test expression is evaluated.

If the result of the expression is true a bloack of statements will be executed.

If the result is false the program continues from the next statement after the if block.

Syntax :



folowchart

Example:





Result:


good Morning!
have a good day!	



if...else statement

Use the if... statement to execute some code if a condition is true and another code if the condition is false.

It executes some code if a condition is true and another code if the condition is false.


Syntax:


Folowhart



Example:


Result:


  Have a good day!



if...elseif...else Statement

This statement specifies a new conditon to test, if the first condition is false

The if...elseif...else a special statement that is used to combine multiple if...else statements


Syntax:

Folowchart:

Example:



Result:


Have a nice day! 



Switch statement

selects one of many blocks of code to be executed

To select one of many blocks of code to be executed, use the Switch statement. The switch statement is used to avoid long blocks of if..elseif..else code.

The switch statement works in an unusual way. First it evaluates given expression then seeks a label to match the resulting value.

If a matching value is found then the code associated with the matching label will be executed or if none of the labels match then statement will execute any specified default code.

Syntax:



Example:



Result:


  Today is Monday

Read also:

  • PHP-for-loop Statement
  • PHP-while-loop Statement
  • PHP-do-while-loop Statement
  • PHP-Fore-each-loop Statement

  • aimtocode