Things you don't know about php switch

黄舟
Release: 2023-03-11 11:20:01
Original
1747 people have browsed it

switchThe conventional usage is to pass a parameter and compare it with the case one by one;

switch (variable) {
    case 'value':
        // code...
        break;
    
    default:
        // code...
        break;
}
Copy after login

When there are many branches; switch is better than if else if is easy to use; for example;

if('value'){
    // code...
}else if('value2'){
    // code...
}else if('value3'){
    // code...
}else if('value4' || 'value5'){
    // code...
}
Copy after login

If you write it with switch, you can pass true; each case is equivalent to an else if;

switch ('value') {
    case 'value1':
        // code...
        break;
    case 'value2':
        // code...
        break;
    case 'value3':
        // code...
        break;
    case 'value4':
    case 'value5':
        // code...
        break;
}
Copy after login

However, it should be noted that switch is a loose comparison; that is to say, the following code can satisfy every case;

switch (123) {
    case 'string':
        // code...
        break;
    case 'string2':
        // code...
        break;
    case 'string3':
        // code...
        break;
}
Copy after login

The way to solve this problem is to convert it to string when passing parametersstring type;

switch (strval(123)) {
    case 'string':
        // code...
        break;
    case 'string2':
        // code...
        break;
    case 'string3':
        // code...
        break;
}
Copy after login

Things you dont know about php switch

The above is the detailed content of Things you don't know about php switch. 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