Lovelock
Lovelock

Reputation: 8075

Setting a variable from the result of a foreach loop

i am trying to create a variable that will contain an email list created from a foreach loop.

Currently the PHP is like so:

  // select all the emails from the users that are subscribed the email list
  $query = "SELECT * FROM users WHERE email_list = 0";
  $query_params = array(); 
  try { 
  $stmt = $db->prepare($query); 
  $result = $stmt->execute($query_params);
  } 
    catch(PDOException $ex) 
  { 
    die("Failed to run query: " . $ex->getMessage()); 
  } 
  $rows = $stmt->fetchAll();
  foreach($rows as $row):
    $email = $row['email'];
    echo "$email, ";
  endforeach;

That echo creates e.g.

email1, email2, email3 etc.

But what i want is to be able to set a variable that i can use after the foreach which will contain all of the emails.

I have tried using a function and then setting a variable with the function being called.

Something like this:

  function createEmailList() {
    $rows = $stmt->fetchAll();
    foreach($rows as $row):
      $email = $row['email'];
      echo "$email, ";
    endforeach;
  }
  echo createEmailList();

But as you can imagine that doesn't work.

Thanks, Craig.

Upvotes: 1

Views: 190

Answers (3)

Richie
Richie

Reputation: 1439

Here's the trick

function createEmailList() {
// fetch rows from DB
    foreach($rows as $row){
        $emails[] = $row['email'];
    }
return $emails;
}

Upvotes: 2

Marc Anton Dahmen
Marc Anton Dahmen

Reputation: 1091

 function createEmailList($stmt) {
     $emails = array();
     foreach($stmt->fetchAll() as $row) {
         $emails[] = $row['email'];
     }
     return implode(', ', $emails);
 }
 echo createEmailList($stmt);

Upvotes: 2

developerwjk
developerwjk

Reputation: 8659

First, you have to pass your $stmt into the function. Otherwise, $stmt doesn't exist as far as the function knows.

Secondly, echoing out email in a loop is not going to put it into a variable as a list. You need to concatenate it into a string variable (or something) not just echo it out.

Third, if you want the function to be called like echo createEmailList(...); then it needs to return a value.

Fourth, I hate vb-style syntax for a foreach, so I changed it to normal syntax below.

 function createEmailList($stmt) 
 {
    $rows = $stmt->fetchAll();
    $emailS = '';
    foreach($rows as $row)
    {
      if($emailS!='')
      {
         //so it doesn't add the comma before first email 
         //nor after last email
         $emailS .= ', ';
      }
      $emailS .= $row['email'];
    }
    return $emailS;
  }
  echo createEmailList($stmt);

Upvotes: 2

Related Questions