简体   繁体   中英

Include the result of a Foreach loop in a variable in PHP ? ( for the function mail() )

I'm French so I might not speak English very well.

I'm trying to "put" the result of a foreach loop in a variable like this:

$msg = '<html><head>
        <title>Commande de photos</title>
 </head><body>
        <p>Voici la liste des photos demand&eacute;es :<br />
 <ul> HERE I WANT TO "PUT" THE RESULT OF THE FOREACH LOOP</ul>';

Here is my foreach loop:

foreach($tab as $val){
echo('<li>'.$val.'</li>');
}

Then the $msg enter in the composition of the function mail() like this:

mail($destinataire,$sujet,$msg,$headers);

So how can I do this to include the result of foreach in a message because I have already a bug?

$msg = '<html><head><title>Commande de photos</title></head><body><p>Voici la liste des photos demand&eacute;es :</p><ul>';
foreach($tab as $val){
     $msg .= '<li>' . $val . '</li>';
}
$msg .= '</ul>';
mail($destinataire,$sujet,$msg,$headers);

The trick here is the .= concatenation operator. For example:

$x = 'abc';
echo $x; // echoes 'abc'
$x .= 'def';
echo $x; // echoes 'abcdef'

Like so?

$list = '';
foreach($tab as $val){
    $list .= '<li>'.$val.'</li>';
}

$msg = '<html><head>
    <title>Commande de photos</title>
</head><body>
    <p>Voici la liste des photos demand&eacute;es :<br />
<ul>'.$list.'</ul>';

mail($destinataire,$sujet,$msg,$headers);
ob_start();
// here your loop echo'ing stuff
$content = ob_get_clean();

See php man pages for more info on ob_* functions

Not so much an answer - but davethegr8's answer worked for me! I am attemting my first php template system intergration using Savant3 and this helpped keep all the logic seperate from the template file. Thanks!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM