Home > Backend Development > PHP Tutorial > An example of the difference between if else and else if in php

An example of the difference between if else and else if in php

伊谢尔伦
Release: 2023-03-11 07:58:01
Original
3294 people have browsed it

In php if can use direct if else or ElseIf to determine other possible situations. Let’s introduce if else and ElseIf There are differences in usage and some details.

If…Else Statement

If you want to execute some code when a certain condition is true and other code when the condition is not true, use the if….else statement.

Syntax

if (condition) //设置条件
  code to be executed if condition is true; //如果条件为真的代码被执行;
else
  code to be executed if condition is false;  //如果条件为假,代码被执行
Copy after login

Example 1
If the current date is Monday, the following code will output "Happy Monday.", otherwise it will output "Happy Every Day.":

<?php
$d=date("D"); //变量d赋值
if($d=="Mon"){
 echo "星期一快乐!";
}else{
 echo "天天快乐!";
}
?>
Copy after login

Example 2

If d is equal to 1, output "number 1", otherwise output "number is not 1"

<?php
$d=2; //变量d赋值
if($d==1){
 echo "数字1"; //变量d等于1时输出的值
}else{
 echo "数字不是1"; //不等于1时输出的值
}
?>
Copy after login

ElseIf statement

If you want to be in multiple To execute the code when one of the conditions is true, please use the elseif statement:

Syntax

if (condition) //条件1
  code to be executed if condition is true; //条件1为真,代码被执行
elseif (condition) //条件2
  code to be executed if condition is true; //条件2为真,代码被执行
else
  code to be executed if condition is false;  //2个条件都为假时,代码被执行
Copy after login

Example

When the value of d is equal to 1, output "number 1"; equal to 2 When the two conditions are not met, it outputs "No matching number"

<?php
$d=3; //变量d赋值
if($d==1){
 echo "数字1"; //当d等于1时输出“数字1”
}
elseif ($d==2){
 echo "数字2"; //当d等于2时输出“数字2”
}
else{
 echo "没有符合的数字"; //两个条件都不成立时输出的内容
}
?>
Copy after login

Summary: in if else and ElseIf, if can include else and elseif, but if after using if else Otherwiseif will not appear but the opposite will work.

The above is the detailed content of An example of the difference between if else and else if in php. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template