I"m having trouble receiving a list of items that are checked in a field of checkboxes which are part of a form.
I have an HTML table with a few checkboxes:
HTML
<input type="checkbox" name="carry[]" value="1" />
<input type="checkbox" name="carry[]" value="2" />
<input type="checkbox" name="carry[]" value="3" />
PHP - this is what I'm using to post the form to an email address
foreach($_POST as $key => $val) {
$body .= $key . " : " . $val . "\r\n";
I get the value in my email as: "carry: Array" -- not the actual values that are selected. How do I handle an array of checkboxes selected in a form and post it?
Ideally, I would want: "carry: 1; 2; 3" (without the quotes)
You can check if the value is an array and handle it differently:
foreach($_POST as $key => $val) {
if (is_array($val)) {
$body .= $key . " : " . implode(",",$val) . "\r\n";
} else {
$body .= $key . " : " . $val . "\r\n";
}
}
If you want the string '1; 2; 3', you should join together the items in the array:
$carry= implode('; ', $_POST['carry']);
However doing so will naturally cause ambiguous results if any of the items in the array themselves have a semicolon in.
To iterate over the post array allowing any of its members to be arrays:
foreach($_POST as $key=>$val) {
if (is_array($val))
$val= implode('; ', $val);
$body.= "$key: $val\r\n";
}
Or, if you don't need so much control over the exact formatting and a debugging dump is fine (but you need to see more than just the useless string 'Array':
$body= var_export($_POST, TRUE);
It's printing carry: Array because that's exactly what it is. You need to loop over it (another loop inside the first) to access the values inside:
foreach($_POST as $key => $val) {
if($key == 'carry') {
foreach($val as $carry) {
$body .= $carry;
}
}
else {
$body .= $key . " : " . $val . "\r\n";
}
}
That's completely untested but hopefully the logic is sound :)
Related
I have an array:
$instructions = array (
array("step_no"=>"1","description"=>"Ensure that you have sufficient balance"),
array("step_no"=>"2","description"=>"Approve the request sent to your phone")
);
What I want is to loop through this array, which I have done, but I am now confused because I don't know how to get the output I desire.
foreach ($array as $key => $value) {
//echo $key . "\n";
foreach ($value as $sub_key => $sub_val) {
if (is_array($sub_val)) {
//echo $sub_key . " : \n";
foreach ($sub_val as $k => $v) {
echo "\t" .$k . " = " . $v . "\n";
}
} else {
echo $sub_key . " = " . $sub_val . "\n";
}
}
}
The above code loops through the array, but this line of code:
echo $sub_key . " = " . $sub_val . "\n";
gives me:
step_no = 1 description = Ensure that you have sufficient balance step_no = 2 description = Approve the request sent to your phone
when I change it to:
echo $sub_val . "\n";
it gives me:
1 Ensure that you have sufficient balance 2 Approve the request sent to your phone
But I what I truly want is:
1. Ensure that you have sufficient balance
2. Approve the request sent to your phone
Is this possible at all? Thanks.
$instructions = array (
array("step_no"=>"1","description"=>"Ensure that you have sufficient balance"),
array("step_no"=>"2","description"=>"Approve the request sent to your phone")
);
foreach($instructions as $instruction) {
echo $instruction['step_no'] . '. ' . $instruction['description'] . "\n";
}
If it's HTML you may want to use <ol> and <li>.
It smells like you are not running this script in command line but in browser. If so, then \n makes no visual effect (unless within <pre> block) and you u must use HTML tag <br /> instead. Also, drop concatenation madness and use variable substitution:
echo "{$sub_key}. = {$sub_val}<br/>";
You can simple achieve this way
<?php
$instructions = array (
array("step_no"=>"1","description"=>"Ensure that you have sufficient balance"),
array("step_no"=>"2","description"=>"Approve the request sent to your phone")
);
foreach($instructions as $instruction){
echo $instruction['step_no'].'. '.$instruction['description'].PHP_EOL;
}
?>
Alway keep it simple.
I am using json_decode and echoing the values using a nested foreach loop.
Here's a truncated json that I am working on:
[{"product_name":"Product 1","product_quantity":"1","product_price":"2.99"},....
and the loop
foreach($list_array as $p){
foreach($p as $key=>$value) {
$result_html .= $key.": ".$value."<br />";
}
}
This was I am able to echo all key/value pairs.
I have tried using this to echo individual items something like:
foreach($list_array as $p){
foreach($p as $key=>$value) {
echo "Product: ".$p[$key]['product_name'];
echo "Quantity: ".$p[$key]['product_quantity'];
}
}
However I am unable to because it doesn't echo anything.
I would like to be able to show something like:
Product Name: Apple
Quantity: 7
Currently it is showing:
product_name: Apple
product_quantity: 7
How can I remove the key and replace it with a predefined label.
It can be done with:
foreach ($list_array as $p){
$result_html .= 'Product: ' . $p->product_name
. 'Quantity: ' . $p->product_quantity . '<br />';
}
If you are decoding your json into an object you can do it like that.
$list_array = json_decode('[{"product_name":"Product 1","product_quantity":"1","product_price":"2.99"}]');
$result_html = '';
foreach($list_array as $p){
$result_html .= '<div>Product: '.$p->product_name.'</div>';
$result_html .= '<div>Quantity: '.$p->product_quantity.'</div>';
}
echo $result_html;
I've noticed that this code in PHP 5.5 only displays the fields that have a value. It entirely skips the blank ones and won't display their name or value:
$msg = '';
foreach($_POST as $key => $value) {
$msg .= $key . ': ';
if (is_array($value)) {
foreach($value as $arr_value){
$msg .= $arr_value . "; ";
}
} else {
$msg .= $value;
}
$msg .= "\n";
}
echo $msg;
Is there a way to loop and also see the names of the fields that had no values entered when the form was submitted? Thanks.
Update: The form has this enctype. Could this make a difference? enctype="multipart/form-data"
I use this code to retrieve all the post request (refer below)
<?php
foreach ($_POST as $key => $value) {
$body .= $key . ": " . $value . '<br>';
}
echo $body;
?>
and there is a post data named "adminemail" and "cat", now what i want is to eliminate those two and print all the post data except those two. How to do that? any suggestions, recommendations and ideas, would love to hear. Thank you in advance.
option 1
unset($_POST['adminemail'],$_POST['cat']);
option 2
<?php
foreach ($_POST as $key => $value) {
if(!in_array($key,array('adminemail','cat'))){
$body .= $key . ": " . $value . '<br>';
}
}
echo $body;
?>
The following should work:
<?php
$arr = array_diff_key($_POST, array("adminemail" => 0, "cat" => 0));
$body = ""; // You must have this line, or PHP will throw an "Undefined variable" notice
foreach($arr as $key => $value){
$body .= $key . ": " . $value . "<br/>";
}
echo $body;
?>
I have 20 "sets" of input fields in my HTML Form.
Here is a taster:
<input id="a1height" />
<input id="a1width" />
<input id="a1length" />
<input id="a1weight" />
<input id="a2height" />
<input id="a2width" />
<input id="a2length" />
<input id="a2weight" />
...and so on
Now, I need a way of:
a) storing all the values in one variable with pipes(|) between the height, width, length & weight and \n between each set
b) if one or more of the fields in a set is incomplete my variable $errors is set to true.
I'm at a little bit of a loss on how I can achieve this. Never really good with loops :'(
Can someone explain how to do this?
Many thanks!!
Here is a solution using an $errors array that stores all errors and an $all string that contains your desired output. To check, put var_dump( $all); at the end of the script.
$errors = array();
$all = '';
// Loop over the values 1 through 20
foreach( range( 1, 20) as $i)
{
// Create an array that stores all of the values for the current number
$values = array(
'a' . $i . 'height' => $_POST['a' . $i . 'height'],
'a' . $i . 'width' => $_POST['a' . $i . 'width'],
'a' . $i . 'length' => $_POST['a' . $i . 'length'],
'a' . $i . 'weight' => $_POST['a' . $i . 'weight']
);
// Make sure at least one submitted value is valid, if not, skip these entirely
if( count( array_filter( array_map( 'is_numeric', $values))))
{
// This basically checks if there's at least one numeric entry for the current $i
continue; // Skip
}
// Validate every value
foreach( $values as $key => $value)
{
if( empty( $value))
{
$errors[] = "Value $key is not set";
}
// You can add more validation in here, such as:
if( !is_numeric( $value))
{
$errors[] = "Value $key contains an invalid value '$value'";
}
}
// Join all of the values together to produce the desired output
$all .= implode( '|', $values) . "\n";
}
To nicely format the errors, try something like this:
// If there are errors
if( count( $errors) > 0)
{
echo '<div class="errors">';
// If there is only one, just print the only message
if( count( $errors) == 1)
{
echo $errors[0];
}
// Otherwise format them into an unordered list
else
{
echo '<ul>';
echo '<li>' . implode( '</li><li>', $errors) . '</li>';
echo '</ul>';
}
echo '</div>';
}
First should create NAME properties for your inputs, as these will be used in the _POST array to specify your values.
<input id="a1height" name="a1height" />
<input id="a1width" name="a1width" />
<input id="a1length" name="a1length" />
<input id="a1weight" name="a1weight" />
<input id="a2height" name="a2height" />
<input id="a2width" name="a2width" />
<input id="a2length" name="a2length" />
<input id="a2weight" name="a2weight" />
Then, after you submit, loop through the post array creating your pipe-joined varibles
$errors = false;
$string = "";
$current_prefix = '';
foreach($_POST as $key=>$posted_value){
if(trim($posted_value)==""){ //if the value is empty or just spaces
$errors = TRUE;
}
//find out if we need to add a new line
$number = preg_replace ('/[^\d]/', '', $key) //get the numbers of the name only
if ($current_prefix != $number){
$string .= "\n";
} else {
$string .= '|';
}
$string .= $posted_value;
}
Create an array to store your values.
Loop through your input fields, parsing the prefix (ie 'a1') from the field type (ie 'height')
Insert the values into the array like this:
$your_array['a1']['height'] = $_POST['a1height'];
Remember to validate and sanitize your input.
You can change your html so the posted fields come in a nicely formatted array:
<input name="a1[height]" />
<input name="a1[width]" />
<input name="a1[length]" />
<input name="a1[weight]" />
<input name="a2[height]" />
<input name="a2[width]" />
<input name="a2[length]" />
<input name="a2[weight]" />
That way you get an array that's easy to use. You could access $_POST['a1']['height'] or $_POST['a1']['length'] or $_POST['a2']['height'].