How can you optimize PHP code for better performance when checking for existing usernames?

When checking for existing usernames in PHP, it is important to optimize the code for better performance by using efficient data structures and algorithms. One way to do this is by utilizing a database index on the username column to speed up the search process. Additionally, you can consider caching the results of previous username checks to avoid redundant database queries.

// Assuming $username contains the username to be checked
// Connect to the database
$pdo = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");

// Prepare a SQL statement to check for existing username
$stmt = $pdo->prepare("SELECT COUNT(*) FROM users WHERE username = :username");
$stmt->bindParam(':username', $username);
$stmt->execute();

// Fetch the result
$count = $stmt->fetchColumn();

// Check if the username already exists
if ($count > 0) {
    echo "Username already exists!";
} else {
    echo "Username is available!";
}