How can associative arrays be utilized in PHP to streamline code and avoid lengthy switch-case statements?
Using associative arrays in PHP can help streamline code by mapping key-value pairs to avoid lengthy switch-case statements. Instead of writing multiple cases for different conditions, you can simply look up the value associated with a key in the array. This makes the code more concise and easier to maintain.
// Example of using an associative array to streamline code
$actions = [
'login' => 'loginFunction',
'logout' => 'logoutFunction',
'register' => 'registerFunction',
];
$action = 'login'; // Example action
if (array_key_exists($action, $actions)) {
$functionName = $actions[$action];
$functionName(); // Call the function associated with the action
} else {
// Handle unknown action
echo 'Unknown action';
}
function loginFunction() {
echo 'Login function called';
}
function logoutFunction() {
echo 'Logout function called';
}
function registerFunction() {
echo 'Register function called';
}