free classified ads and leads
domain website price


Switch vs Match in PHP

PHP

Switch vs Match in PHP

Switch Statement

Basic syntax of a switch statement :

switch (expression)
{

case value1:
 // code to execute if expression equals value 1
 break;
case value2;
 //code to execute if expression equals value 2
 break;
default:
 // code to execute if none of the above cases match
}

Example :

$dayofweek =4;
switch($dayofweek)
{
case 1:
echo "its monday";
break;
case 2:
echo "its tuesday";
break;
case 3:
echo "its wedneshday";
break;
case 4:
echo "its thursday";
break;
case 5:
echo "its friday";
break;
default:
echo "its the weekend";

}

Match Expression

Basic syntax of a match statement:

$result = match ( expression)
{
value1 =>expression1, value2 => expression2,  // additional cases

default=>expression_default

};


$dayofweek = 4;
$result=match ($dayofweek)
{
1=>"its monday",
2=>"its tuesday",
3=>"its wednesday",
4=>"its thursday",
5=>"its friday",
default=> "its the weekend"
}


echo $result;   /// its thursday

 

Type Safety

The match expression in PHP is more type-safe compared to the switch statement. In a switch statement, loose type comparisons can lead to unexpected behavior, but the match expression enforces strict type checking. A match arm compares values strictly ( === ) instead of loosely as the switch statement does.

 

$value=1;
switch ($value)
{

case 1:
echo "integer 1";
break;
case "1":
echo "string '1'";
break;

}

// output integer 1


$value ="1";

$result=match($value){ 
1=>"integer 1",
"1"=>"string '1'",
};

echo $result;

// output : string '1'

 

"Fall through " Behavior

In a switch statement, if you forget to use break after a case, execution "falls through" to the next case , potentially causing unintended behavior. The match expression doesn't have this issue.

Exhaustiveness checking

the match expression enforces exhaustive checking, meaning you need to cover all possible cases. If you miss a case, PHP will generate a warning or error.

 

Bookmark and Share




Gallery

Related Topics

Comments



Submit Reviews:


(Enter the characters seen on the image below.)



Promotional Ads

Advertisement

Movers and Packers Zirakpur
zirakpur
Zirakpur

ShreeJi Packers and Movers Chandigarh
Booth No. 6, Plot No. 2212 Pipli Wala Town, Manimarjra, Chandigarh
Chandigarh