Conditional Statements in PhP

1. If, else and ifelse:
<? PHP
$num = 1;
If ($num ==1) /*checks if the name is equal to 1, if not it will go to the else if statement */
{
Echo "the number is 1"."<br/>";
}
elseif ($num<1) /*checks if the name is less than one or else it will go to the else statement */
{
Echo "the number is less than one"."<br/>";
}
Else
{
Echo "if and else if dint work "."<br/>";
}

2. Conditional statement using ternary operators:

    <?php                                                                            $nums=15;    
$true = "it's true";
$false = "it's false";
echo ($nums<=16)?$true:$false; /* checks if nums is less than 16. If yes then it will return $true value or else it will return $false value.*/
?>

3. For loop:

<?php                                                                            for($count=1; $count<=5; $count++)                                               
{
echo"$count"."<br/>"; //print the value of count for each iteration
if($count==4)
{
echo "you have reached 4"."<br/>";

break; //breaks out of the loop if the count value reaches 4
}
}

4. Switch Statement: 
Switch statement is a better version of if else statement. You might want to use the switch statement if you want to jump right to the answer. If an answer is found , it breaks out of the switch statement.

<?php                                                                                $status = "online";    
switch($status)
{
case online: /*this statement will be executed and breaks out of the switch since the status value is online.*/
echo "you are online now";
break;
case offline:
echo "you are offline now";
break;
case logout;
echo "you are logged out";
break;
}
?>

5.While and Do while:
In do while, the code is executed and after that the condition is checked. It means if you use do while your code will be executed atleast one time irrespective of the condition. But in while loop, the condition is checked first and after that if it satisfies the condition , the code will be executed. See the examples below.

<?php

$value = 0;
do //execution starts here without checking the condition
{
echo $value."<br/>";
$value++;
}
while($value<=10); //checks the condition after one successful execution
$max = 1;
while ($max<10)
{
echo $max."<br/>";
$max++;
}
?>

Other Interesting Blogs

Leave a Comment

0 Shares
Share via
Copy link