How can the substring function be utilized in PHP to extract and count email domains from a database?
To extract and count email domains from a database in PHP, you can use the substring function to extract the domain part of each email address and then keep track of the count using an associative array. By looping through the database results, you can extract the domain from each email address and increment the count for that domain in the array.
// Assuming $dbResult contains the database results with email addresses
$domainCount = array();
foreach ($dbResult as $row) {
$email = $row['email'];
$domain = substr($email, strpos($email, '@') + 1);
if (array_key_exists($domain, $domainCount)) {
$domainCount[$domain]++;
} else {
$domainCount[$domain] = 1;
}
}
print_r($domainCount);