Branch Function: If-else-elseif functions |
| Written by phpecho.com | |||
Branching statements are the most commonly used conditional statements in any programming language. PHP is no different. The two main branching functions used are the if construct and the switch construct. We will look at the if construct in this tutorial. Branching logic is used where you need to provide alternative program flow for different situations. For example, suppose you need to print Even or Odd based on the type of number input. So the program flow would be something like this: 1. Get the input The statements 3 and 4 above will involve the use of branching statements. The if conditions consists of two parts: the condition which returns a boolean value and the statements that will execute if boolean value is true. There are three different ways the if construct is used. The first case is when we need to perform an operation under a particular situation. Consider this example below: <?php
echo ("Example <br>");
$string1 = "test";
$string2 = "test";
$string3 = "testing";
if (strcmp($string1,$string2) == 0)
echo("String 1 and string 2 are the same");
?>
The output of this program is: Example The if construct here checks if the two strings are equal and if they are it prints "String 1 and string 2 are the same". This is one usage. If you notice, this code does not do anything if the two strings are not equal. To handle this scenario, we add the else clause. Now our program looks like this: <?php
echo ("Example <br>");
$string1 = "test";
$string2 = "test";
$string3 = "testing";
if (strcmp($string1,$string2) == 0)
echo("String 1 and string 2 are the same");
else
echo("String 1 and string 2 are not the same");
?>
This handles the scenario but not good enough for us to test! We can use the following example to test the if-else construct: <?php
echo ("Example <br>");
$string1 = "test";
$string2 = "test";
$string3 = "testing";
if (strcmp($string1,$string2) == 0)
echo("String 1 and string 2 are the same");
else
echo("String 1 and string 2 are not the same");
if (strcmp($string2,$string3) == 0)
echo("<br>String 2 and string 3 are the same");
else
echo("<br>String 2 and string 3 are not the same");
?>
Now consider another situation where we need to use multiple if's and else's. This is where we will use the elseif construct. It is also very straightforward. Consider this example below: <?php
echo ("Example <br>");
$string1 = "test";
$string2 = "test";
$string3 = "testing";
if (strcmp($string1,"testing") == 0)
echo("String 1 is testing");
elseif(strcmp($string2,"testing") == 0)
echo("String 2 is testing");
elseif(strcmp($string3,"testing") == 0)
echo("String 3 is testing");
?>
We have used multiple if statements and the statement following the construct that satisfies the condition is executed. Also note that the statements following the if condition can be enclosed within braces. In that case, there can be multiple statements for each if construct.
|