What is the correct syntax for parsing an array in PHP switch statements?
When using a switch statement in PHP, you cannot directly pass an array as the expression to be evaluated. However, you can achieve the desired functionality by using a foreach loop to iterate through the array elements and then perform the switch logic within the loop. This allows you to switch on each element of the array individually.
$array = [1, 2, 3];
foreach ($array as $element) {
switch ($element) {
case 1:
echo "One";
break;
case 2:
echo "Two";
break;
case 3:
echo "Three";
break;
default:
echo "Unknown";
break;
}
}
Keywords
Related Questions
- What is the impact of the register_globals setting on PHP form variables?
- What are the common pitfalls to avoid when working with nested arrays in PHP, especially in scenarios involving permission hierarchies?
- What potential security risks are involved in using PHP to access and download files from external sources?