Home  >  Article  >  Backend Development  >  Things you don't know about php switch

Things you don't know about php switch

黄舟
黄舟Original
2017-06-25 09:53:081746browse

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;
}

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...
}

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;
}

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;
}

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;
}

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!

Statement:
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