oscurodrago
oscurodrago

Reputation: 808

switch with preg_match return true if string is empty

i've a problem with a switch and a preg_match case my code is like this

switch( $WORD ){

    case ( preg_match("/^(?:.+-)?(\d+?)$/i",  $WORD , $ID )  ? true : false ):
        echo "valid ". $ID ." test -> " .preg_match("/^(?:.+-)?(\d+?)$/i",  $WORD );
    break;

    default:
        echo $WORD;
    break;
}

these code work well with

$WORD = "TEST";        print => TEST
$WORD = "TEST-1";      print => valid 1 test -> 1
$WORD = "TEST-2552";   print => valid 2552 test -> 1
$WORD = "343";         print => valid 343 test -> 1

but if $WORD is null or $WORD = "" the case is true too and it print

$WORD = "";      print => valid  test -> 0

how i can fix it? i've tried with

case ( ( preg_match("/^(?:.+-)?(\d+?)$/i",  $WORD , $ID ) == 1 )  ? true : false ):

but dosne't work

Upvotes: 0

Views: 3610

Answers (3)

oscurodrago
oscurodrago

Reputation: 808

i've resolved it with a simple trick so if some one have the same problem that is a way to resolve it ... ( at the moment i don't know if exist a better way )

Just before the case with preg_match add a case like case "":

switch( $WORD ){

    default:
    case "":
        // call a function
    break;

    case preg_match("/^(?:.+-)?(\d+?)$/i", $WORD, $ID ) ? true : false:
        echo "valid and id is: ". $ID ;
    break;

    // all other common cases
    case "home":
    case "dog":
    case "cat":
    case "fish":
        // call a function
    break;

    case "bull":
    case "shark":
    case "somethingelse":
        // call a function
    break;
 }

Upvotes: 2

farmer1992
farmer1992

Reputation: 8156

i cant understand why you are using switch to select a boolean

when $WORD is "" , switch($WORD) equals switch(false)

then your problem happens

why not

if(preg_match("/^(?:.+-)?(\d+?)$/i",  $WORD , $ID )){
echo "valid ";
}else{
echo $WORD;
}

Upvotes: 0

Till Helge
Till Helge

Reputation: 9311

This is not how switch was meant to be used and I'm not even sure if it could work this way. The whole idea of switch is to have a short notation for chained if-statements.

if ($foo == 1) { ... }
else if ($foo == 2) { ... }
else if ($foo == 3) { ... }
else { ... }

becomes

switch ($foo) {
   case 1: ... break;
   case 2: ... break;
   case 3: ... break;
   default: ...
}

Especially when having a very complex condition in $foo you can save a lot of duplicated code. In your case using switch does not really make a lot of sense. Just go with if and you are good to go:

if (preg_match("/^(?:.+-)?(\d+?)$/i",  $WORD , $ID )) {
    echo "valid ". $ID ." test -> " .preg_match("/^(?:.+-)?(\d+?)$/i",  $WORD );
} else {
    echo $WORD;
}

Upvotes: 0

Related Questions