Home > Article > Backend Development > Things you don't know about php switch
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; }
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!