How can arrays and switch statements be utilized to improve the efficiency and readability of PHP code?
Using arrays and switch statements can improve the efficiency and readability of PHP code by providing a structured way to handle multiple conditions or options. Arrays can store data in a structured format, making it easier to manage and access different values. Switch statements can be used to compare a variable against multiple values in a more concise and organized manner compared to using multiple if-else statements.
// Example of using arrays and switch statements to handle different cases
// Define an array of options
$options = ['option1', 'option2', 'option3'];
// Variable to determine the current option
$selectedOption = 'option2';
// Switch statement to handle different cases based on the selected option
switch ($selectedOption) {
case 'option1':
echo 'Option 1 selected';
break;
case 'option2':
echo 'Option 2 selected';
break;
case 'option3':
echo 'Option 3 selected';
break;
default:
echo 'Invalid option selected';
}