PHP

Decision Making in php if, ifelse, switch case statements

Decision Making

Decision Making:- One of the most useful aspects of a programming language is the ability to do different actions in different situations. I use an umbrella if it rains today, but if it’s sunny I wear my sunglasses. When the light is red I stop; when it is green I go, and when it is yellow I go fast. In this tutorial, you learn how to use different conditional statements to make the program observe differently depending on the situation.

Amazon Purchase Links:

Top Gaming Computers

Best Laptops

Best Graphic Cards

Portable Hard Drives

Best Keyboards

Best High Quality PC Mic

Computer Accessories

*Please Note: These are affiliate links. I may make a commission if you buy the components through these links. I would appreciate your support in this way!

Php Decision Making IF statement:

The most recognizable conditional or Decision Making statement is the if statement. You use the if statement to tell the program to execute some code if a given condition is true. Optionally, you can add an else statement that tells the program what to do if the condition is not true


Decision Making If Statements

The most basic if statement consists of the condition that is being figured out along with the code to be executed inserted in curly braces This is how you write a basic if statement:

if (some condition) {

some lines of PHP code here;

that are performed;

if the condition evaluated to true;

}

Example how to use Decision Making If statement in PHP

<html>
<head>
<title> Basic If Statements </title>
</head>
<body>
<h1>Day Report</h1>
<?php
$day = 'sunday';
if ($day == 'sunday') {
echo '<p>today is sunday.go to sleep.</p>';
}
?>
</body>
</html>

Decision Making

In the above example you Noticed that when you check to see if the weather is rainy, you use a double equal sign (==) and that all the PHP statements still end with a semicolon, although the if statement itself does not have a semicolon.

“Note: there is a common error to use a single equal sign in conditional statement because single equal sign(=) is the assignment operator and the double equal sign in comparison operator”

Now, of course, it is always rainy with that code. If you make the day sunny, nothing displays because that code is never executed. If you want to have code execute if the Decision Making or condition is not met, you add an else statement. Else statements never live on their own. They must always follow an if statement. The following code shows the syntax of an if statement with an else statement.

if (some condition) {

Some lines of PHP code here;

That are performed;



php Decision Making  If Else

if the condition evaluated to true;

} else {

Some lines of PHP code here;

That are performed;

if the condition did not evaluate to true;

}

So now the code performs some action whatever the weather. If the weather is rainy then the output tells you to use your umbrella. Otherwise, it tells you to wear your sunglasses. Because of the variable the weather is set to sunny, you are told to wear your sunglasses.

<html>
<head>
<title> If Else</title>
</head>
<body>
<h1>Day Report</h1>
<?php
$day = 'monday';
if ($day == 'sunday') {
echo '<p>Today is sunday. go to sleep.</p>';
} else {
echo '<p>today is Monday the student are ready to go school.</p>';
}
?>
</body>
</html>

Decision Making

You can add a condition or Decision Making on the else statement by turning it into a Decision Making elseif statement. In the following code, if it is not Sunday today, you check to see if it is actually Monday before you decide go to school. After you know it is Monday, you perform your actions and jump to the bottom of the if statement.

<html>

<head>

<title> elseif </title>

</head>

<body>

<h1>Weather Report</h1>

<?php

$weather = 'sunny';

if ($weather == 'rainy') {

echo '<p>It will be rainy today. Use your umbrella.</p>';

} elseif ($weather == 'sunny') {

echo '<p>It will be sunny today. Wear your sunglasses.</p>';

} elseif ($weather == 'snowy') {

echo '<p>It will be snowy today. Bring your shovel.</p>';

} else {

echo '<p>I don’t know what the weather is doing today.</p>';

}

?>

</body>

</html>

Decision Making


Decision Making Comparison Operators for If Else Statements

So far you have just been using the equal comparison operator, but conditional statements are really checking to see if a statement evaluates to true, not if something is equal. You can also check to see if something is not equal to something, less than something else, more than something, and so on. Strings that consist of numbers are converted to numeric before the test except for the identical. As shown in the below Table that has a list of comparison operators

Decision Making

Some if statements can become complex as you perform actions within the conditional statement itself. Because the conditional statement is testing for “true” and anything that is not false is true, you have a wide range of conditions that you can test for.

 Examples of how to use different comparison operator in different ways that you use in if statements.

<head>
<title> comparison operators </title>
</head>
<body>
<h1>If Statements</h1>
<?php
$a = 5;
$b = 8;
$c = 58;
$d = 40;
$date = date('D, M d, Y');
if ($d < 50) {
if ($a >= strlen($data)) {
echo '<p>Position 1:'. $a .'</p>';
}
echo '<p>Position 2:' . $d . '</p>';
if (($d + $b) < ($c - $a)) {
echo '<p>Position 3: ' . ($d + $b) . '</p>';
} else {
echo '<p>Position 4: ' . ($c - $a) . '</p>';
}
}
?>
<div>
<?php if ($date) { ?>
<p>Today is <?php echo $date; ?>.</p>
<p>You can check to see if there’s something in a variable before you print it.<p>
<p>You can also jump in and out of PHP in the middle of an if statement.</p>
<?php  } ?>
</div>
</body>
</html>

Decision Making If Else with Ternary Operator

You can use a shortcut syntax with simple if-then-else statements that can make your code easier to read, especially if you are interspersing it in HTML code. The following code does a simple test for gender:

<?php
$gender = 'F';
if ($gender == 'M') {
echo 'Man';
} else {
echo 'Woman';
}
?>
This same code can be written using the ternary operator (?) as:
<?php
$gender = 'F';
echo ($gender == 'M') ? 'Man' : 'Woman';

Decision Making

Ternary stands for three parts. This statement consists of the condition in parentheses followed by the ternary operator (the question mark), then the result-if-the-condition-is-true separated with a colon from the result-if-the-condition-is-false. Notice that there is no if in the ternary if statement at all as can be seen in the previous statement and in the following syntax statement:

(condition) ? whentrue : whenfalse;

/This shorthand version of if/else is useful as well when assigning defaults. In the following code, if a variable is empty, you give it a value; otherwise you use whatever is in the variable:

<?php

echo (empty($_GET[‘task’])) ? ‘home’ : $_GET[‘task’];

 

?>


Decision Making LOGICAL OPERATORS in PHP

Sometimes you need to look at multiple conditions before you decide to execute a block of code.

<?php
$weather = 'sleeting';
if ($weather == 'snowing') {
echo '<p>Something is falling from the sky.</p>';
} elseif ($weather == 'sleeting') {
echo '<p>Something is falling from the sky.</p>';
} elseif ($weather == 'raining') {
echo '<p>Something is falling from the sky.</p>';
} elseif ($weather == 'sunny') {
echo '<p>I need my sunglasses.</p>';
} elseif ($weather == 'partly sunny') {
echo '<p>I need my sunglasses.</p>';
} else {
echo '<p>The weather is ' . $weather .'.</p>';
}
?>

Decision Making

The same actions are performed whether it is snowing, sleeting, or raining. Imagine that that code block was 20 lines long. That is a lot of extra code, not to mention there is a greater chance for errors and more work to maintain it.

Instead of the multiple if statements, you can link together multiple Decision Making OR conditions. In this case, you want to say that something is falling from the sky if it is snowing, sleeting, or raining. Here is how that works.

<?php
$weather = 'sleeting';
if ($weather == 'snowing' OR $weather == 'sleeting' OR $weather == 'raining') {
echo '<p>Something is falling from the sky.</p>';
} elseif ($weather == 'sunny' OR $weather == 'partly sunny') {
echo '<p>I need my sunglasses.</p>';
} else {
echo '<p>The weather is ' . $weather .'.</p>';
}
?>

 

 

Decision Making

When using the OR operator, the Decision Making OR condition is true if any of the conditions are true. The OR operator is case insensitive and can also be written as ||. This vertical bar symbol is called a double pipe symbol. This code is identical to the preceding code as you can in output:

<?php
$weather = 'sleeting';
if ($weather == 'snowing' || $weather == 'sleeting' || $weather == 'raining') {
echo '<p>Something is falling from the sky.</p>';
} elseif ($weather == 'sunny' || $weather == 'partly sunny') {
echo '<p>I need my sunglasses.</p>';
} else {
echo '<p>The weather is ' . $weather .'.</p>';

}
?>

Decision Making

In the same way, you use the Decision Making AND operator when you need all conditions to be true before executing a block of code. This code produces output as shown in below output section:

<?php
$author = 'khan';
$title = 'love is blind ';
if ($author == 'khan' AND $title == 'love is blind') {
echo '<p>Found the book.</p>';
} else {
echo '<p>'.$title.' by '. $author .' is the wrong book.</p>';

}
?>

Decision Making

Instead of using AND you can use the symbol &&, which gives you the same result as the previous example, as shown in output.

<?php
$author = 'khan';
$title = 'love is blind ';
if ($author == 'khan' && $title == 'love is blind') {
echo '<p>Found the book.</p>';
} else {
echo '<p>'.$title.' by '. $author .' is the wrong book.</p>';

}
?>

Decision Making


You can mix AND and OR as needed as shown here. See in output section.

<?php
$city = 'Springfield';
$state = 'MA';
if ($city == 'Springfield' AND ($state == 'MA' OR $state =='VT')) {
echo '<p>This Springfield is in Massachusetts or Vermont.</p>';
} else {
echo '<p>$city, $state is not Springfield in MA or VT.</p>';
}

?>

Decision Making

There is a slight difference between AND/OR and &&/||. The words AND/OR have lower operator precedence than the symbols &&/||, which for practical purposes means that you do not want to mix the word version and the symbol version in the same statement or you could get unexpected results.

Just as in regular mathematics, you can use parentheses to change the precedence order, to improve readability, or when there is any ambiguity. The final logical operator is the not (!) operator. Use this to negate. The following code tells you to

put away your umbrella if it’s not rainy, otherwise, it tells you it is raining. See in below output.

<?php
$weather = ‘sunny’;
if (!($weather == ‘rainy’)) {
echo “<p>Put away your umbrella.</p>”;
} else {
echo “<p>It’s raining!</p>”;
}

Decision Making SWITCH STATEMENTS

Decision Making switch statements are also used to perform specific blocks of code depending on conditions. They are used when you want to compare the same variable or expression to several different values. Take, for example, the following series of if statements:

<html>
<head>
<title> switch statements </title>
</head>
<body>
<h1>Weather Report</h1>
<?php
$weather = ‘sunny’;
if ($weather == ‘rainy’) {
echo “<p>It will be rainy today. Use your umbrella.</p>”;
} elseif ($weather == ‘sunny’) {
echo “<p>It will be sunny today. Wear your sunglasses.</p>”;
} elseif ($weather == ‘snowy’) {
echo “<p>It will be snowy today. Bring your shovel.</p>”;
} else {
echo “<p>I don’t know what the weather is doing today.</p>”;
}
?>
</body>
</html>

Decision Making



Each if statement is comparing to the variable $weather. With a Decision Making switch statement you write the same code in a clearer fashion. The following code performs the same functions:

<html>
<head>
<title> switch statements </title>
</head>
<body>
<h1>Weather Report</h1>
<?php
$weather = 'sunny';
if ($weather == 'rainy') {
echo '<p>It will be rainy today. Use your umbrella.</p>';
} elseif ($weather == 'sunny') {
echo '<p>It will be sunny today. Wear your sunglasses.</p>';
} elseif ($weather == 'snowy') {
echo '<p>It will be snowy today. Bring your shovel.</p>';
} else {
echo '<p>I don’t know what the weather is doing today.</p>';
}
?>
</body>
</html>

The syntax of the switch statement is as follows:

switch ($variable) {

case value1:

code to be executed if $variable is equal to value1;

break;

case value2:

code to be executed if $variable is equal to value2;

break;

default:

code to be executed if $variable is different from both value1 and value2;

}

The switch ($variable) establishes what is compared. Each of the case statements lists a value. Notice that the case statements end with a colon. This is the normal practice, though a semicolon works as well. If the variable in the switch statement matches the value in the case statement, the associated block of code is performed. The break; tells the program to jump to the end of the switch block, ignoring all the rest of the case statements. If you want to perform some action when the value matches and then get out, use the break;. The default statement at the end is always performed unless an earlier matching case contained a break. If you want to have two or more values perform the same actions, skip the break on the first value. It then drops through and executes the lines (regardless of matching any subsequent case statements) until it finds a break. In the following code the state is ISB, so after it gets a match, it displays “Islamabad” because it continues until it finds a break;.

<?php
$state = 'ISB';
switch ($state) {
case 'KPK':
case 'KHI':
case 'AAW':
echo '<p> Karachi </p>';
break;
case 'LHE':
case 'ISB':
case 'JAG':
echo '<p> Islamabad </p>';
break;
default:
echo '<p>$state is not in Pakistan.</p>';
}

Decision Making


Decision Making ALTERNATIVE SYNTAX

There is an alternative syntax for the control structures: the if and switch statements that you already know as well as the control statements you learn in the next lesson. Curly braces have a tendency to get lost in long stretches of code, especially if you are hopping in and out of PHP and HTML. You often end up with lines that look like this:

<?php } ?>

This alternative syntax replaces the curly braces with a colon and an end word. The syntax for an if statement is as follows:

if (condition) :

some lines of PHP code here;

that are performed;

if the condition evaluated to true;

elseif (condition) :

some lines of PHP code here;

else :

some lines of PHP code here;

endif;

The switch statement uses this syntax:

switch ($variable) :

case value1:

code to be executed if $variable is equal to value1;

break;

case value2:

code to be executed if $variable is equal to value2;

break;

default:

code to be executed if $variable is different from both value1 and value2;

endswitch;


The recommendation is to use this syntax if you are mixing HTML and PHP on a page and to use the curly brace syntax if you are doing straight PHP.

Engr Fahad

My name is Shahzada Fahad and I am an Electrical Engineer. I have been doing Job in UAE as a site engineer in an Electrical Construction Company. Currently, I am running my own YouTube channel "Electronic Clinic", and managing this Website. My Hobbies are * Watching Movies * Music * Martial Arts * Photography * Travelling * Make Sketches and so on...

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button