How can one optimize the code for comparing values from an array with values in a MySQL table in PHP to improve performance?

When comparing values from an array with values in a MySQL table in PHP, one way to optimize the code for better performance is to use a single query to fetch all the values from the MySQL table and then compare them with the values in the array in PHP. This reduces the number of database queries and improves efficiency.

// Assuming $array contains values to compare with MySQL table

// Connect to MySQL database
$mysqli = new mysqli("localhost", "username", "password", "database");

// Fetch values from MySQL table
$query = "SELECT column_name FROM table_name";
$result = $mysqli->query($query);
$mysql_values = [];
while ($row = $result->fetch_assoc()) {
    $mysql_values[] = $row['column_name'];
}

// Compare values from array with values from MySQL table
foreach ($array as $value) {
    if (in_array($value, $mysql_values)) {
        // Value exists in MySQL table
        echo "$value exists in MySQL table. ";
    } else {
        // Value does not exist in MySQL table
        echo "$value does not exist in MySQL table. ";
    }
}

// Close MySQL connection
$mysqli->close();