Switch and Case for strpos() in PHP
Sometimes we need to check multiple strings for the presence of a specific piece of text. In many cases, the switch statement may be a perfect fit for this.
In this tutorial, I will show how to use switch and case with the strpos() function in PHP.
Use true
inside the switch and check in every case if the strpos()
result is !== false
.
Example:
<?php
$text = 'My favorite color is red.';
switch (true) {
case strpos($text, 'blue') !== false:
echo 'Picked color: blue.';
break;
case strpos($text, 'red') !== false:
echo 'Picked color: red.';
break;
case strpos($text, 'green') !== false:
echo 'Picked color: green.';
break;
}
?>
Output: Picked color: red.