How can a foreach loop be effectively used to populate an array with data from a database in PHP?

When populating an array with data from a database in PHP, a foreach loop can be effectively used to iterate over the result set and store each row as an element in the array. This allows for easy access to the data and manipulation within the PHP script.

// Assume $db is a PDO object connected to the database
$statement = $db->query("SELECT * FROM table_name");
$results = $statement->fetchAll(PDO::FETCH_ASSOC);

$dataArray = array();
foreach ($results as $row) {
    $dataArray[] = $row;
}

// $dataArray now contains all rows from the database table