How can database queries be optimized to filter data before loading it into an array in PHP?

When working with large datasets in PHP, it is important to optimize database queries to filter data before loading it into an array. This can be achieved by using SQL queries with conditions to only retrieve the necessary data from the database. By filtering data at the database level, we can reduce the amount of data transferred and processed in PHP, resulting in improved performance and efficiency.

// Example of optimizing database queries to filter data before loading into an array
$pdo = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");

// Query to retrieve only the required data
$stmt = $pdo->prepare("SELECT column1, column2 FROM mytable WHERE column3 = :value");
$stmt->execute(['value' => 'filter_value']);

// Fetch data into an array
$data = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Process the data as needed
foreach ($data as $row) {
    // Do something with $row['column1'] and $row['column2']
}