PHP input array question - php

I have a form which includes 3 date of birth inputs like the following:
<label>Date of Birth</label>
<input type='text' size='2' maxlength='2' name='DOB[2]' />
<input type='text' size='2' maxlength='2' name='DOB[3]' />
<input type='text' size='4' maxlength='4' name='DOB[1]' />
The order of the inputs work as month/day/year. I am sending this to my script which then implodes the DOB array like such (Thanks to #Matt H.):
if(isset($_userData['DOB']))
$_userData['DOB'] = implode('-', $_userData['DOB']);
Now, the problem is, this implodes it to the improper format of month/day/year, which is not the order of the array I set, but the order of the inputs. Am I stuck with having to manually concatenate the array into the format I need for MySQL (year/month/day) ?

Sort the array first:
if(isset($_userData['DOB'])) {
ksort($_userData['DOB']);
$_userData['DOB'] = implode('-', $_userData['DOB']);
}

Try:
if(isset($_userData['DOB'])){
ksort($_userData['DOB']);
$_userData['DOB'] = implode('-', $_userData['DOB']);
}
This will sort the array $_userData['DOB'] by key. Based on your input elements, it is going to become:
$_userData['DOB'] = array(
1 => 'YYYY',
2 => 'MM',
3 => 'DD'
);

Related

PHP: How to loop and retrieve values of multiple inputs of form with the different name attribute? [duplicate]

I am trying to send data from multiple checkboxes (id[]) and create an array "info" in php to allow me to run a script for each value (however the quantity of values may change each time) however first I am trying to display the content of each array value. I am not quite sure how to put my array populating line to save all the content to the array.
HTML
echo("<input name='id[]' type='checkbox' value='".$shopnumb."'>");
my hopeful processing code currently is -
$info=$_POST['id[]'];
Echo(array_values($info));
what do I need to do to make the content sent by post from the form checkboxes populate the array info
any help is greatly appreciated
edited for clarification.
Change
$info=$_POST['id[]'];
to
$info=$_POST['id'];
by adding [] to the end of your form field names, PHP will automatically convert these variables into arrays.
You should get the array like in $_POST['id']. So you should be able to do this:
foreach ($_POST['id'] as $key => $value) {
echo $value . "<br />";
}
Input names should be same:
<input name='id[]' type='checkbox' value='1'>
<input name='id[]' type='checkbox' value='2'>
...
On the form page, field names must look like this
<input name="id[]" type="checkbox" value="x">
<input name="id[]" type="checkbox" value="y">
<input name="id[]" type="checkbox" value="z">
On the destination page, $_POST['id'] is your array variable
$id = implode(",", $_POST['id']);
echo $id; //Should print "1,2,3"
You cannot echo an array directly, because it will just print out "Array". If you wanna print out the array values use print_r.
print_r($_POST['id']);
I don't know if I understand your question, but maybe:
foreach ($_POST as $id=>$value)
if (strncmp($id,'id[',3) $info[rtrim(ltrim($id,'id['),']')]=$_POST[$id];
would help
That is if you really want to have a different name (id[key]) on each checkbox of the html form (not very efficient). If not you can just name them all the same, i.e. 'id' and iterate on the (selected) values of the array, like: foreach ($_POST['id'] as $key=>$value)...

Foreach $_POST - how to increase array pointer to the next element

I'm looping through the $_POST array (generated form elements) and I need to get the keys and values of the next elements in my foreach loop.
Edit: The name of the elements for the answers (i.e canbeanynameABC and canbeanynameXYZ) are always unknown.
Here is an example array:
Array (
[inputid] => 87 [inputoutputtype] => radio [canbeanynameABC] => radio answer 2
[inputid] => 88 [inputoutputtype] => radio [canbeanynameXYZ] => radio answer 4 )
My code here
foreach ($_POST as $key => $value) {
switch ($key) {
case "inputid":
echo "<br/>Value of input_id : " . $value;
next($_POST);
echo "<br/>Value of inputoutputtype : " . $value;
next($_POST);
echo "<br/>Value of answer : " . $value;
break;
}
}
I thought that by doing next($_POST), the pointer would now be positioned on the next key/value.
Apparently it doesn't work, i'm getting the following displays:
Value of input_id : 87
Value of input_output_type : 87
Value of answer : 87
Any help would be greatly appreciated. Thanks
Edit: It was suggested that I use arrays to organize my form elements/values. I still can't figure out how to use arrays so that each answer (value) returned from the form, I actually get three values (answer, inputid, inputoutputtype)
Edit: #CBroe I spent the afternoon trying to figure out how to use arrays in $_POST. The form can contain any number of elements, and these elements can be text, radio, select/option, checkbox (can have more than one value returned). Each "value" I get from this form must be associated with an "inputid" and an "inputoutputtype". These form and elements are generated using php, so i'm trying to build a php form handler that will read any numbers of elements and types. The generator is creating unique names for each element so that values don't get overwritten. I'm trying to figure out how to integrate arrays into the generator, but not sure if I'll be able to assign them a row number (i.e [0], [1]..).. maybe I'm just not seeing how arrays would work for my situation.
Update: Ok, now i'm trying to modify my php form handler to deal with elements that could have any names. I need to be able to read id, type and value (3 different values) from element filled out in the form.
I'm playing around with the form (even though its entirely generated), but not sure what to name my elements
<input type='hidden' name='inputradio[inputid]' value='1'>
<input type='hidden' name='inputradio[inputoutputtype]' value='radio'>
<input type='radio' name='inputradio[output]' value='Radio answer 1'>
<input type='hidden' name='inputradio[inputid]' value='2'>
<input type='hidden' name='inputradio[inputoutputtype]' value='radio'>
<input type='radio' name='inputradio[output]' value='Radio answer 2'>
<input type='hidden' name='inputtext1[inputid]' value='3'>
<input type='hidden' name='inputtext1[inputoutputtype]' value='text'>
<input type='text' name='inputtext1[output]' value='Text answer 1'>
<input type='hidden' name='inputtext2[inputid]' value='4'>
<input type='hidden' name='inputtext2[inputoutputtype]' value='text'>
<input type='text' name='inputtext2[output]' value='Text answer 2'>
Should I change the title of this post if the direction changed a but?
Thanks
C
There are only two properties to an entry in $_POST, the key and the value. I don't know where you got your example array, but it doesn't work like that. So if I had a radio button group with all sharing the same name, I would get the name->value pair.
If I created the following form and I submitted it with value a selected in the radio button group:
<form method="POST" >
<input type="text" name="textbox" value="test"><br/>
a.<input type="radio" name="rd" value="a"><br/>
b.<input type="radio" name="rd" value="b"><br/>
c.<input type="radio" name="rd" value="c"><br/>
<input type="submit" value="submit">
</form>
my $_POST would contain the following values:
Array
(
[textbox] => test
[rd] => a
)
if I tried to step through my array, I would do so as follows:
for ($_POST as $key->$value) {
echo $key . " = " . $value . "\n";
}
Which would give me the following output:
textbox = test
rd = a
Can you tell me what problem you are trying to solve, since it seems you are approaching this from the point of view of some other language or framework, or possibly you are looking to work with some other array in PHP that is not $_POST?

How to use data from jquery appended dependent inputs in a form

Not sure that the title I choose is very explicit. If not, sorry.
My question is if we have a form with dependent inputs like so:
<form>
<input type='text' name='item-1'/>
<input type='text' name='sub-item-1'/>
<input type='text' name='sub-item-2'/>
</form>
In this case, the sub items are directly associated with the item above.
Now, we add 2 buttons to this form.
First one will add (jQuery append) an input sub item, in this case it will be:
<input type='text' name='sub-item-3'/>
Second button will add (also jQuery append) a all new item with its own sub items.
So we could end up with something like this:
<form>
<input type='text' name='item-1'/>
<input type='text' name='sub-item-1'/>
<input type='text' name='sub-item-2'/>
<input type='text' name='sub-item-3'/>
<input type='text' name='item-2'/>
<input type='text' name='sub-item-1'/>
<input type='text' name='sub-item-2'/>
</form>
If I use a submit button the "dependecy" of the data wouldn't pass. So I end up with something like this:
array(
item-1 => random value A,
sub-item-1 => random value B,
sub-item-2 => random value C,
etc)
So my question is how can I end up with an array which translate the dependecy of the data. Like so for example:
array(
Value item 1 => array(
sub-item-1 => random value B,
sub-item-2 => random value C)
Value item 2 => array(
sub-item-1 => random value B))
etc
Appreciate anu feedback on an other structure for the form, or a method to structure the data after. Important thing is ending up with an array that shows the dependency of the inputs.
Well hope it's clear enough, try my best.
First of all, the name attribute of your form inputs need to be all unique. So instead of "sub-item-1" for each "parent" you could do "sub-item-1-1", and for the next one, "sub-item-2-1".
Here's some code which would take such an array and reorganize it in a 2-d array (just swap your inputValues with your $_POST)
$inputValues = array(
'item-1'=>'parent 1',
'sub-item-1-1'=>'sub value 1-1',
'sub-item-1-2'=>'sub value 1-2',
'item-2'=>'parent 2',
'sub-item-2-1'=>'sub value 2-1'
);
$outputArray = array();
//create array of parents
foreach($inputValues AS $key=>$value){
if(is_numeric($key[5])){
array_push($outputArray,array('parent'=>$value));
}
}
//add children
foreach($inputValues AS $key=>$value){
if(is_numeric($key[9])){
$parentIndex = $key[9]-1;
$outputArray[$parentIndex][$key] = $value;
}
}
print_r($outputArray);
Edit: Just realized this wouldn't work if your item count goes into the double-digits - if so, use substring to extract the item/parent number from the key name instead of "$key[5]" or "$key[9]"

$_POST Array from html form

I am trying to send data from multiple checkboxes (id[]) and create an array "info" in php to allow me to run a script for each value (however the quantity of values may change each time) however first I am trying to display the content of each array value. I am not quite sure how to put my array populating line to save all the content to the array.
HTML
echo("<input name='id[]' type='checkbox' value='".$shopnumb."'>");
my hopeful processing code currently is -
$info=$_POST['id[]'];
Echo(array_values($info));
what do I need to do to make the content sent by post from the form checkboxes populate the array info
any help is greatly appreciated
edited for clarification.
Change
$info=$_POST['id[]'];
to
$info=$_POST['id'];
by adding [] to the end of your form field names, PHP will automatically convert these variables into arrays.
You should get the array like in $_POST['id']. So you should be able to do this:
foreach ($_POST['id'] as $key => $value) {
echo $value . "<br />";
}
Input names should be same:
<input name='id[]' type='checkbox' value='1'>
<input name='id[]' type='checkbox' value='2'>
...
On the form page, field names must look like this
<input name="id[]" type="checkbox" value="x">
<input name="id[]" type="checkbox" value="y">
<input name="id[]" type="checkbox" value="z">
On the destination page, $_POST['id'] is your array variable
$id = implode(",", $_POST['id']);
echo $id; //Should print "1,2,3"
You cannot echo an array directly, because it will just print out "Array". If you wanna print out the array values use print_r.
print_r($_POST['id']);
I don't know if I understand your question, but maybe:
foreach ($_POST as $id=>$value)
if (strncmp($id,'id[',3) $info[rtrim(ltrim($id,'id['),']')]=$_POST[$id];
would help
That is if you really want to have a different name (id[key]) on each checkbox of the html form (not very efficient). If not you can just name them all the same, i.e. 'id' and iterate on the (selected) values of the array, like: foreach ($_POST['id'] as $key=>$value)...

How to POST data as an indexed array of arrays (without specifying indexes)

i'm having some problem with posting data as an array of array. This is how i'd like my data to be POSTED:
array(
['someName'] =>
array([0] =>
array(['description'] =>890
['valore'] =>444)
[1] =>
array(['description'] =>98090
['value'] =>77)
)
I know i can achieve this if my html is like this:
<input type='text' name="someName[0][value]">
<input type='text' name="someName[0][description]">
<input type='text' name="someName[1][value]">
<input type='text' name="someName[1][description]">
My problem is that the input fields are on rows of a table and the user can add/remove as many rows as he want, so i can't have fixed index (or i have to modify the name of the input fields each time a row is added since every time i add a row i clone the upper row in the table)
So what i am asking is one of these two things:
1) is there a way to post data the way i want without specifing an index
2)if not, how can i modify dynamically the new input field so that they have an updated name with the new index?
EDIT - i had alredy tried using name="someName[value][]" and name="someName[description][]" but the output is not the desired one:
array(['terreniOneri'] =>
array(['descrizione'] =>array([0] =>890
[1] => 98090)
['valore'] =>array([0] =>444
[1] =>677)
)
i know i can iterate on this array in php i was just wondering if i could avoid it.
Do it the way you put in the question. If the user removes some row, your form elements would be:
<form action="..." method="post" onsubmit="return reindexer(this);">
<input type='text' name="someName[0][value]">
<input type='text' name="someName[0][description]">
<input type='text' name="someName[2][value]">
<input type='text' name="someName[2][description]">
</form>
But there's no problem to traverse an array with non-contiguous numeric indexes in php: use a foreach loop.
<?php
if (count($_POST['somename']) > 0)
{
foreach ($_POST['somename'] as $row)
{
echo "Value: ".$row['value']."<br />\n";
echo "Description: ".$row['description']."<br />\n";
}
}
If you need to know the number of each row as a continous index (in the example provided, row 0 would still be 0, but row 2 should be 1 (as the user deleted one row), you can use a variable acting as a counter:
<?php
if (count($_POST['somename']) > 0)
{
$i = 0;
foreach ($_POST['somename'] as $row)
{
echo "Index $i<br />\n";
echo "Value: ".$row['value']."<br />\n";
echo "Description: ".$row['description']."<br />\n";
$i++;
}
}
I think this approach has more sense that the other solutions, as this way you would have an array of items, being each item a value and a description, instead of having two separate arrays of values and descriptions and having to get the values for your item from those two arrays instead of one.
edit: I've modified the first piece of code to include the <form> element. This would be the accompanying js function:
<script type="text/javascript">
function reindexer(frm)
{
var counter = 0;
var inputsPerRow = 2;
for (var idx = 0; idx < frm.elements.length; idx++)
{
elm.name = elm.name.replace('%%INDEX%%', counter);
if (idx % inputsPerRow == 1)
{
// only increment the counter (or row number) after you've processed all the
// inputs from each row
counter++;
}
}
}
</script>
Try like this:
<input type='text' name="someNameValue[]">
<input type='text' name="someNameDescription[]">
If the fields are paired, they can be attached by the indexes. So if you have the 10th row, someNameValue[9] and someNameDescription[9] will be a pair. You can merge them.
EDIT:
You don't have to write the indexes manually, they will be automatically generated.
<input type='text' name="someName[]">
<input type='text' name="someName[]">
<input type='text' name="someName[]">
and
<input type='text' name="someName[0]">
<input type='text' name="someName[1]">
<input type='text' name="someName[2]">
will give the same result in your post array.

Categories