09 January 2011

Php For Beginners (Lesson 5)

In this lesson we will be discussing conditional statements. Conditional statements are used when you want to relate an action with some condition. Php supports four types of conditional statements:

If Statement

Syntax

if (condition)
{ code to be executed }

Example
<?php
$a=5;
if ($a==5)
{
   echo “five”; // outputs “five”
} 
?>
If – else Statement

Syntax

if (condition)
{ code to be executed }
else { code to be executed }

Example
<?php
$a=5;
if ($a==5)
{
   echo “five”; // outputs “five”
}else
{ 
   echo “not five”;
}
?>
If – elseif – else Statement

Syntax

if (condition)
{ code to be executed }
elseif (condition)
   { code to be executed }
else { code to be executed }

Example
<?php
$a=2;
if ($a==5)
{
   echo “five”; 
}elseif ($a==6)
{
   echo “six”; 
}
else 
{ 
   echo “neither five nor six”;  // outputs “neither five nor six”
}
?>
Switch Statement

Syntax

switch (variable)
{
case test1:
  code to be executed if variable =test1;
  break;
case test2:
  code to be executed if variable =test2;
  break;
default:
  code to be executed if n is different from both test1 and test2;


Example
<?php
$a=2;
switch ($a)
{
case 5:
  echo “five”;
  break;
case 2:
  echo “two”; // outputs “two”
  break;
default:
  echo “neither five nor two”;
}  
?>
The switch statement takes variable as an argument and then code to be executed for each case. Whichever condition will be true it will execute its code and if no condition is true then it will execute the default code.

References

http://www.php.net
http://www.w3schools.com

This is all for the fifth lesson, now all you need to do is practice these concepts and if you have any queries then feel free to comment on this post.


next Previous Lesson --- Next Lesson next

No comments: