What is the correct syntax for using multiple values in a switch case in PHP?
When using a switch case in PHP, you can only specify one value per case. However, if you need to match multiple values for a single case, you can achieve this by using an array and the in_array() function within each case statement. This allows you to check if the value being evaluated matches any of the values in the array.
$value = "apple";
switch(true) {
case in_array($value, ["apple", "banana"]):
echo "Fruit is either apple or banana";
break;
case in_array($value, ["orange", "grape"]):
echo "Fruit is either orange or grape";
break;
default:
echo "Fruit is not recognized";
}
Keywords
Related Questions
- What are common errors encountered during the pre-installation check for LimeSurvey on a Linux server?
- How can the use of foreach loops and array_search function be optimized for better performance in similar scenarios?
- What best practices should be followed when sending personalized emails with dynamic content generated in PHP?