Search code examples
phpphpmailer

How to output a forloop in a string?


I am trying to output data object with multiple properties into a string within phpmailer how do I achieve this?

function sendMailTo($mail, $data, $subject_, $toEmail) {
    $body = 'all data:' foreach ($data as $obj) {
        $obj->property;
    }

    $mail->ClearAllRecipients();
    $mail->AddAddress($toEmail);
    $mail->FromName = $data->inputName;
    $mail->From = $email;
    $mail->Subject = $subject_;
    $mail->IsHTML(true);
    $mail->Body = $body;
    $mail->AddReplyTo($toEmail, $data->inputName);
    $mail->send();
}

Solution

  • This code is a bit nonsensical, unless $data is really an array of objects, each having a property called property.

    If you want to extract all the properties of an object, iterate over them, because PHP objects are iterable.

    Also there's no need to use a local variable; assemble the string directly into $mail->Body:

    $mail->Body = "All data:\r\n";
    foreach ($data as $property => $value) {
        $mail->Body .= "$property = $value\r\n";
    }
    

    I've assumed that you want both the property names and values.

    (and you can remove the later line that says $mail->Body = $body;)