regexp in switch statement

PhpSwitch Statement

Php Problem Overview


Are regex's allowed in PHP switch/case statements and how to use them ?

Php Solutions


Solution 1 - Php

Switch-case statement works like if-elseif.
As well as you can use regex for if-elseif, you can also use it in switch-case.

if (preg_match('/John.*/', $name)) {
    // do stuff for people whose name is John, Johnny, ...
}

can be coded as

switch $name {
    case (preg_match('/John.*/', $name) ? true : false) :
        // do stuff for people whose name is John, Johnny, ...
        break;
}

Hope this helps.

Solution 2 - Php

No or only limited. You could for example switch for true:

switch (true) {
    case $a == 'A':
        break;
    case preg_match('~~', $a);
        break;
}

This basically gives you an if-elseif-else statement, but with syntax and might of switch (for example fall-through.)

Solution 3 - Php

Yes, but you should use this technique to avoid issues when the switch argument evals to false:

switch ($name) {
  case preg_match('/John.*/', $name) ? $name : !$name:
    // do stuff
}

Solution 4 - Php

Keep in mind the above answer can be slightly optimized like this:

Changing:

switch $name {
    case (preg_match('/John.*/', $name) ? true : false) :
        // do stuff for people whose name is John, Johnny, ...
        break;
}

To:

switch $name {
    case (bool)preg_match('/John.*/', $name) :
        // do stuff for people whose name is John, Johnny, ...
        break;
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionTotoView Question on Stackoverflow
Solution 1 - PhpbourbakiView Answer on Stackoverflow
Solution 2 - PhpNikiCView Answer on Stackoverflow
Solution 3 - PhpBrandon FrohbieterView Answer on Stackoverflow
Solution 4 - PhpS. DreView Answer on Stackoverflow