PHP If…Else Statements

PHP Conditional Statements

3starinfo.com
Very often when you write code, you want to perform different actions for different decisions. You can use conditional statements in your code to do this.

In PHP we have the following conditional statements:

  • if statement – executes some code only if a specified condition is true
  • if…else statement – executes some code if a condition is true and another code if the condition is false
  • if…else if….else statement – selects one of several blocks of code to be executed
  • switch statement – selects one of many blocks of code to be executed

 

PHP – The if Statement

The if statement is used to execute some code only if a specified condition is true.

Syntax

if (condition)
{
code to be executed if condition is true
;
}
<?php
$a=date(“H”);
if ($a<“10”)
{
echo “hello”;
}
?>

PHP – The if…else Statement

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

Syntax

if (condition)
{
executed if condition is true;
}
else
{
executed if condition is false;
}

Example

<?php
$t=date(“H”);
if ($t<“20”)
{
echo “Have a good day!”;
}
else
{
echo “Have a good night!”;
}
?>

PHP – The if…else if….else Statement

Syntax

if (condition)
{
code to be executed if condition is true;
}
else if (condition)
{
code to be executed if condition is true;
}
else
{
code to be executed if condition is false;
 }
<?php
$t=date(“H”);
if ($t<“10”)
{
echo “Have a good morning!”;
}
else if ($t<“20”)
{
echo “Have a good day!”;
}
else
{
echo “Have a good night!”;
}
?>

The PHP Switch Statement

Use the switch statement to select one of many blocks of code to be executed.

Syntax

switch (n)
{
case label1:
code to be executed if n=label1;
break;
case label2:
code to be executed if n=label2;
break;
default:
code to be executed if n is different from both label1 and label2;
}

Example

<?php
$color=”red”;
switch ($color)
{
case “red”:
echo “Your favorite color is red!”;
break;
case “blue”:
echo “Your favorite color is blue!”;
break;
case “green”:
echo “Your favorite color is green!”;
break;
default:
echo “Your favorite color is neither red, blue, or green!”;
}
?>

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