5. PHP – Conditional Statements.

Posted: September 22, 2013 in Hypertext Preprocessor (PHP)
Tags: ,

Say you want to execute a block of code upon some condition, well, that’s were conditional statements comes handy.

PHP supports the following conditional statements :

1. if statement : Codes in the block (codes within {…}) are executed only if the specified condition is true.

if (condition) {
//codes to be executed.
}

<?php
//1. if statement.
echo "1. if statement.";
echo "<br>";
$x=10;
if ($x > 0) {
echo "This is true <br>";
}
?>

2. if… else statement : Execute one of the block. Block1 if the condition is true. Block2 if the condition is false.

if (condition) {
//codes to be executed.
}
else {
//codes to be executed.
}

<?php
//2. if... else statement.
echo "2. if... else statement.";
echo "<br>";
$x=2013;
if ($x == 2013) {
echo "We are in 2013 <br>";
}
else {
echo "We are not in 2013 <br>";
}
?>

3. if…elseif…else statement : Select one of the blocks to be executed out of many.

if (condition) {
//codes to be executed.
}
elseif {
//codes to be executed.
}
.
.
.
else {
//codes to be executed.
}

<?php
//3. if...elseif...else statement.
echo "3. if...elseif...else statement. <br>";
$mood = "boring";
if ($mood == "sleepy") {
echo "Save the code, and go to sleep <br>";
}
elseif ($mood == "boring") {
echo "Go browse something fun and get back <br>";
}
else {
echo "continue...";
}
?>

4. Switch statement : Select one of the blocks to be executed out of many.

switch (pattern) {
case label1 :
//execute the codes in here if label1==pattern.
break;
case label2 :
//execute the codes in here if label2==pattern.
break;
.
.
.
case labelN :
//execute the codes in here if labelN==pattern.
break;
default :
//execute the codes in here if none of the above label’s match the pattern.
}

<?php
//4. Switch statement.
echo "4. Switch statement. <br>";
$language = "php";
switch ($language) {
case "perl":
echo "We are coding using perl";
break;
case "python":
echo "we are coding using python";
break;
case "javascript":
echo "we are coding using javascript";
break;
default:
echo "We are coding using php";
}
?>
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s