Skip to content
PHP Logo

What is the best way to filter out values from one table that are not present in another table in PHP?

To filter out values from one table that are not present in another table in PHP, you can use a SQL query with a LEFT JOIN and a WHERE clause to only select rows where the value from the first table is not found in the second table. This will effectively filter out any values that do not have a match in the second table.

php
<?php
// Connect to your database
$pdo = new PDO('mysql:host=localhost;dbname=your_database', 'username', 'password');

// SQL query to filter out values not present in another table
$query = "
    SELECT table1.column
    FROM table1
    LEFT JOIN table2 ON table1.column = table2.column
    WHERE table2.column IS NULL
";

// Execute the query
$stmt = $pdo->query($query);

// Fetch and display the results
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
    echo $row['column'] . "<br>";
}
?>