What are the best practices for handling repetitive tasks like checking for existing usernames in PHP scripts?

When handling repetitive tasks like checking for existing usernames in PHP scripts, it is best practice to encapsulate the logic in a reusable function. This not only promotes code reusability but also helps in maintaining a clean and organized codebase. By creating a function to handle this task, you can easily call it whenever needed without duplicating code.

// Function to check for existing usernames
function checkExistingUsername($username) {
    // Perform database query to check if the username already exists
    // Return true if username exists, false otherwise
}

// Example usage
if(checkExistingUsername($username)) {
    echo "Username already exists. Please choose a different one.";
} else {
    echo "Username is available.";
}