Thursday 20 November 2014

PHP Loops & Conditional Statements

PHP Loops


For: We can say for loop is similar to while only difference is that in For loop we already have the information reagarding the no. Of time loop run. But while is applied where we do not have information that how many time loop has to run.

<?php

for($i=0;$i<=10;$i++)

{

echo $i;

echo"<br>";

}

?>

While: PHP "while" loops will run a block of code over and over again as long as a condition is true.


<?php
$i=1;
while($i<=8d)
{
$i++;
echo $i."<br>";
}
?>


Do..While: Do..while is similar like while, only Difference is that in Do..while condition is cheched after the running of each block of code or after the statement.


<?php
$i=1;
do
{
$i++;
echo $i."<br>";
}
while($i<=10);
?>


PHP Conditional Statements


In PHP we have the following conditional statements:


if statement
- executes some code only if a specified condition is true


<?php

$x=10;

if($x==10)

{

echo "Condition is true";

}

?>



if...else statement- executes some code if a condition is true and another code if the condition is false

<?php

$x=10;

if($x=="11")

{

echo "Condition is true";

}

else

{

echo "Condition is False";

}

?>



if...elseif....else statement- specifies a new condition to test if the first condition is false

<?php

$x=30;

if($x=="10")

{

echo "This is if part"; //condition is false

}

elseif($x=="20")

{

echo "This is elseif part"; //condition is false

}

else

{

echo "This is else part"; //condition is true

}

?>



switch statement- selects one of many blocks of code to be executed

<?php
$favcolor = "red";
switch ($favcolor)
{

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!";
}
?>

No comments:

Post a Comment