Home > Backend Development > PHP Tutorial > Detailed explanation of switch usage extension in php

Detailed explanation of switch usage extension in php

伊谢尔伦
Release: 2023-03-11 09:56:02
Original
1216 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

The above is the detailed content of Detailed explanation of switch usage extension in php. For more information, please follow other related articles on the PHP Chinese website!

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