I have a form that looks like this:
<form name="search" method="post" action="http://example.com/search3/">
Seach for: <input type="text" name="find[]" />
Search for stories by Type
<select name="find[]">
<option value="Fiction" selected>Fiction</option>
<option value="Non-Fiction">Non-Fiction</option>
<option value="Essay">Essay</option>
</select>
<input type="submit" name="search" value="Search" />
</form>
on php.search, I get the data by:
$input = array(
"find" => $_POST['find'],
);
It is almost working, except it doesn't put the results in the find array. Instead the data is going into the results in array2, probably b/c i named each field find[]. Here is the var_dump:
array(1) {
["find"]=>
array(2) {
[0]=>
string(5) “testing1”
[1]=>
string(7) “testing2”
}
}
I'm not sure why i leaves the find array blank in this case.
If I change the form so the find[] names as arrays become just find, then I get the data to go into the array named find like i want, HOWEVER, only the select form data will be captured. See var_dump for results and how I only get one result instead of two:
array(1) {
["find"]=>
string(7) “testing2”
}
SO THE QUESTION IS... How can I get the input AND select data captured in the find array?
When naming field using square brackets []
, PHP automatically creates a nested array in the $_POST
(or $_GET
) array.
In your case, the value of $input['find'] is an array that has two numeric keys.
echo $input['find'][0];
echo $input['find'][1];
You can assume that index 0 holds the value entered in text input, the index 1 holds the value selected in the list.
If you skip the squre brackets in field names, browsers sends them to the server as follows:
find=value1&find=value2
PHP, when parsing data, first stores the value1
under the key find
, but when another find
key occurs, it just overwrites the previous value with new value2
.
Try This, This will help you.
The name of fields should not be same.
<form name="search" method="post">
Seach for: <input type="text" name="search" />
Search for stories by Type
<select name="find[]" multiple>
<option value="Fiction" selected>Fiction</option>
<option value="Non-Fiction">Non-Fiction</option>
<option value="Essay">Essay</option>
</select>
<input type="submit" name="submit" value="Search" />
</form>
<?php
if(isset($_POST['submit'])){
$input=array("find"=>$_POST['search'],'search'=>$_POST['find']);
print_r($input);
}
?>
</div>
<form name="search" method="post" action="">
Seach for:
Search for stories by Type
<select name="find[]">
<option value="Fiction" selected>Fiction</option>
<option value="Non-Fiction">Non-Fiction</option>
<option value="Essay">Essay</option>
</select>
<input type="text" name="find[]" />
<input type="submit" name="search" value="Search" />
</form>
<?php if(isset($_POST)){
$input = array();
$var =array();
foreach ($_POST['find'] as $key => $value) {
if(!empty($value)) {
array_push($var, $value);
}
else{
continue;
}
}
$input = array(
"find" => $var,
);
print_r($input);
}