What are some alternative approaches to handling multiple if-else statements in PHP functions?

When dealing with multiple if-else statements in PHP functions, it can lead to code that is difficult to read and maintain. One alternative approach is to use a switch statement, which can make the code more organized and easier to follow. Another approach is to use a mapping array, where the conditions and corresponding actions are stored in an array, making it easier to add or modify conditions without changing the function itself.

// Using a switch statement
function handleRequest($action) {
    switch ($action) {
        case 'action1':
            // code for action1
            break;
        case 'action2':
            // code for action2
            break;
        default:
            // default action
            break;
    }
}

// Using a mapping array
function handleRequest($action) {
    $actions = [
        'action1' => function() {
            // code for action1
        },
        'action2' => function() {
            // code for action2
        }
    ];

    if (array_key_exists($action, $actions)) {
        $actions[$action]();
    } else {
        // default action
    }
}