PHP

Conditional Statement

Written by Anuj kumar

Conditional statements are the set of commands used to performed different  actions based on different conditions.
In PHP we have the following

  • if
  • if else
  • else if
  • switch

if statement
if structure is used for conditional execution of code segment.
Syntax-

Example-

In the above example ,only if the condition “$c>$d” is true, the message “”c is greater than d” is displayed.

Else Statement
The conditional statement  “else”  is used as extension of “if” statement. If the condition fails then it executes another statements under the “else” condition.
Syntax-

Based on the result of expressions, the statements are executed.
Example –

Result – d is greater than c
In the above example in the if condition “$c>$d” is true then the message “c is greater than d” is displayed , else the message “d is greater than c” is displayed.

Else if Condition
else if condition is used as extension of “if” structure if the condition fails then it executes another “If” condition to execute the code segment under the “else if” statement.
Syntax –

Based on the failure “expr 1” condition, “expr 2” is checked and then the statements are executed.

Example –

Output- c is  equal  to d
In the above example the if the condition “$c>$d” is true then the message “c is greater than d” is displayed, else the condition in the else if that is “$c==$d” is evaluated if it is true the message “c is equal to d” is displayed otherwise d is smaller than c is displayed.

Switch Statement
The switch case statement is used to compare a variable or expression values based on which a set of code executed.
Syntax-

Example-

Output-  value of 3 = Default value
In the above example based on the value of $c the messages are displayed of that particular case which matches. The default case accepts anything not matched by other cases, so the value “3” displays the default message.

About the author

Anuj kumar

I'm Anuj kumar a web developer with 4+ year experience .I write blogs in my free time. I love to learn new technologies and share with others. I founded PHPGurukul in September 2015. The main aim of this website to is provide php , jquery , mysql , phpoops and other web development tutorials. I am trying best effort to make PHPGurukul useful for every single moment spend on this website. If you think this website is useful to visit please share with your friend and buddies.