PHP If Else of elsefi statement

  • 2020-05-30 19:42:35
  • OfStack

Conditional statements

When you write code, you often need to perform different actions for different judgments.

You can use conditional statements in your code to do this.

if... else statement

One block of code is executed when the condition holds and another block is executed when the condition does not
elseif statement
With if... else is used in conjunction with the execution of a code block If when a number of conditions 1 is present... Else statement
If you want to execute some code when a condition is true and another code when a condition is not, use if... else statements.

grammar

if (condition)
code to be executed if condition is true;
else
code to be executed if condition is false;

The instance

If the current date is week 5, the following code will output "Have a nice weekend!" , otherwise it will output "Have a nice day!" :


<html>
<body>
<?php
$d=date("D");
if ($d=="Fri")
  echo "Have a nice weekend!"; 
else
  echo "Have a nice day!"; 
?>
</body>
</html>

If you need to execute multiple lines of code when a condition is true or not, you should include these lines of code in curly braces:


<html>
<body>
<?php
$d=date("D");
if ($d=="Fri")
  {
  echo "Hello!<br />"; 
  echo "Have a nice weekend!";
  echo "See you on Monday!";
  }
?>
</body>
</html>

ElseIf statement
If you want to execute the code when one of the conditions holds, use the elseif statement:

grammar


if (condition)
  code to be executed if condition is true;
elseif (condition)
  code to be executed if condition is true;
else
  code to be executed if condition is false; 

The instance
If the current date is week 5, the following example prints "Have a nice weekend!" , if it is a Sunday, output "Have a nice Sunday!" , otherwise output "Have a nice day!" :


<html>
<body>
<?php
$d=date("D");
if ($d=="Fri")
  echo "Have a nice weekend!"; 
elseif ($d=="Sun")
  echo "Have a nice Sunday!"; 
else
  echo "Have a nice day!"; 
?>
</body>
</html>


Related articles: