Sebastian Kopiczko Sebastian Kopiczko - 3 months ago 8
PHP Question

Preg_match in switch case in PHP?

I am making switch function in php and I wonder if is it possible to make one of the cases like that:

switch($message){
case 'hi':
$output = $jsonWelcome;
break;
case preg_match('/start/', $message):
$output = $jsonHelp;
break;
}


I want to execute that last case when $message would be for example: "project start" or "start project". I think that's because preg_match return 0 or 1. Is there any way to make this code works?

Answer
switch($message){
        case 'hi':
            $output = $jsonWelcome;
            break;
        case (preg_match('/start/', $message) ? true : false):
            $output = $jsonHelp;
            break;
}

Should work fine.

Example working code: http://sandbox.onlinephpfunctions.com/code/99ab518718ce9488277619a33dbfdf353f0c2316

Comments