Natsu
Natsu

Reputation: 131

Exclude array data from foreach loop

I have a payment function that emails me whenever a transaction occurs, the issue is it emails me too much data, and not all of it is relevant. The payment itself is processed by Authorize API (which is also whats returning this data).

function sent_mail($data = array()) {
    $out = "";
    foreach ($data as $k => $value) {
        if (is_array($value)) {
            foreach ($value as $key => $v) {
                $out .= ucwords($key) . ' Name : ' . $v . "<br/>";
            }
        } else {
            $out .= ucwords($k) . ' : ' . $value . "<br/>";
        }
    }
    $msg = "<h2><strong>Receipt Of Payment</strong></h2>" . "<br/><br/>";
    $msg .= "$out";

    $to = '[email protected]';
    $subject = 'New Payment';
    $headers = "MIME-Version: 1.0\r\n";
    $headers .= "Content-Type: text/html; charset=iso-8859-1\n";
    @mail($to, $subject, $msg, $headers);
}

The email I get, includes these fields:

DataValue, DataDescriptor, InvoiceID, Amount, Item_name, Item_Desc, FirstName, LastName, Email, Website, Country, Zip, Terms, TransID, Card_Holder

Where as, the only data I need is

InvoiceID, Amount, Item_name, FirstName, LastName, Email, Website

I've not sure how to limit this, create a skip?

Upvotes: 0

Views: 194

Answers (1)

Sumurai8
Sumurai8

Reputation: 20737

In a loop you can use the continue statement to immediately go to the next iteration of that loop. That means you can create a condition to skip over the loop that adds data to your email if the key does not match one of the keys you want to include.

if (!in_array($k, ['InvoiceID', 'Amount', 'Item_name', 'FirstName', 'LastName', 'Email', 'Website'])) {
  continue;
}

Upvotes: 1

Related Questions