Home > Backend Development > PHP Tutorial > A brief discussion on the use and differences of if and switch in PHP learning

A brief discussion on the use and differences of if and switch in PHP learning

little bottle
Release: 2023-04-06 12:22:01
forward
2865 people have browsed it

This article mainly talks about the use and difference between if and switch. It has certain learning value. Interested friends can learn about it.

This is the if statement:

if (条件表达式1){  //条件判断
    //n多语句1
}else if(条件表达式2){
    //n多语句2
}else if(条件表达式3){
    //n多语句3
}
...
...
else{
    //n多语句n
}
Copy after login

Execution process: If conditional expression 1 is true, n multiple statements 1 will be output, otherwise conditional expression 2 will be judged, and so on, if n-1 judgments are made are all false, then output n multiple statements n

It can be seen that if is used for conditional judgment, has scope, and can be used to limit the input data

This is a switch statement:

switch (表达式){   //表达式通常为变量,对case的语句进行匹配
    case 情况1: //这里为冒号不是分号
        n多语句;
        break;  //跳出switch语句
    case 情况2:
        n多语句;
        break;
        ...
        ...
    default:
        n多语句;
}
Copy after login

Working principle:

  1. Perform a calculation on the expression (usually a variable)
  2. Compare the value of the expression with the case n in the structure
  3. If there is a match, execute the code associated with the case
  4. After the code is executed, the break statement prevents the code from jumping into the next case to continue execution
  5. If no case is true, use the default statement

switch tendency to match a certain predetermined value, for example, clicking a certain link in a web page will jump to a certain address without conditional judgment

And switch does not support float or Boolean types.

Related tutorials: PHP video tutorial

The above is the detailed content of A brief discussion on the use and differences of if and switch in PHP learning. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
php
source:cnblogs.com
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template