How To Check String In Switch Case

Quick Summary
- Cast each case to a string with (string) so a PHP switch compares text, since switch uses loose comparison.
- Only the cast on the number 8 matters: without it, PHP before version 8 converts 8balls to 8 and matches the wrong case.
- PHP 8 already compares numbers with non-numeric strings as text, and its match expression offers strict comparison without casting every case.
A PHP switch compares values with loose comparison (==), so strings and numbers can match in ways you don’t expect. Casting each case to a string with (string) keeps the check a plain string comparison.
$ball = "8balls";
switch( $ball ){
case (string) "9balls":
echo "NINE BALLS";
break;
case (string) 8:
echo "8 Balls";
break;
case (string) "8balls":
echo "Eight Balls";
break;
default:
echo "Just Balls";
break;
}How it works
$ball holds the string 8balls, and PHP checks each case from top to bottom:
"9balls"doesn’t match.(string) 8becomes the string"8". Since"8balls"isn’t a numeric string, the two are compared as text and don’t match."8balls"matches, so the snippet printsEight Balls.defaultwould printJust Ballsif nothing matched.
Why the cast matters
The casts on the two string literals change nothing, since they’re already strings. The one that matters is on 8. Without it, the case would compare "8balls" == 8. Before PHP 8, PHP converted "8balls" to the number 8 for that comparison, so the switch would print 8 Balls. PHP 8 compares a number with a non-numeric string as strings, so the result there is Eight Balls. With the cast, you get the same result on every version.
If you want strict comparison without casting every case, PHP 8’s match expression compares values with ===. For the statement itself, start with these basic PHP switch case examples.
Related articles
- PHP’s data types: strings and integers, the two types this comparison mixes

