Reputation: 817
I'm developing a simple contact form.
I have an associative array $_POST['hid']
. Something like this:
Array["0" => "Location0", "1" => "Location1", "2" => "Location2"]
I'm trying to send this array as an email with a view on client side as:
Locations:
I'm using this PHP code but it returns me only the last element from the array in the email...
for ($i = 0; $i < count($_POST['hid']); $i++) {
$a=$_POST['hid'][$i];
}
$email_content .= "Locations:\n$a\n";
Also I tried to send $_POST['hid']
but it returns me Array
in the email.
So the question is how can I send all array values via POST method and receive them in the email. Not just first or last element. Thank you for your help.
Upvotes: 1
Views: 258
Reputation:
You need to use something like this:
$a = 'Locations:<ul>';
for ($i = 0; $i < count($_POST['hid']); $i++) {
$a .= '<li>' . $_POST['hid'][$i] . '</li>';
}
$a .= '</ul>';
$email_content = $a;
Upvotes: 0
Reputation: 2327
Just add a dot (.) before $a
$a = 'Locations:<ul>';
for ($i = 0; $i < count($_POST['hid']); $i++) {
$a .= '<li>' . $_POST['hid'][$i] . '</li>';
}
$a .= '</ul>';
$email_content = $a;
Upvotes: 2
Reputation: 852
for ($i = 0; $i < count($_POST['hid']); $i++) {
$a=$_POST['hid'][$i];
$email_content .= "Locations:\n$a\n";
}
you change the variable $a all the time, that's why you have always the same value.
you can do it by a shorter way also like:
for ($i = 0; $i < count($_POST['hid']); $i++) {
$email_content .= "Locations:\n".$_POST['hid'][$i]."\n";
}
or more clean (to me) like:
foreach($_POST['hid'] as $location) {
$email_content .= "Locations:\n$location\n";
}
EDIT: but the result isn't the one expected so more like this:
$email_content .= "Locations:\n";
$locations = "";
foreach($_POST['hid'] as $location) {
$locations .="$location\n";
}
$email_content .= $locations;
Upvotes: 2
Reputation: 190
$hid = $_POST['hid'];
for ($i = 0; $i < count($hid); $i++) {
$a=$hid[$i];
$email_content .= "Locations:\n$a\n";
}
Or you can use foreach, goes like this:
$hid = $_POST['hid'];
foreach ($hid as $h){
$a=$h[$i];
$email_content .= "Locations:\n$a\n";
}
Upvotes: 0
Reputation: 2350
I'd probably do this instead:
$array = []
array_map(function($item) use (&$array){
$array[] = $item;
},$_POST['hid']);
$array should contain all your values
Upvotes: 0