I have dropdown fields on an event website with variable names so I'm unsure on how to capture the data with $_POST
An example is
tkt-slctr-qty-346[]
tkt-slctr-qty-358[]
Is there a way to capture the data with $_POST by using wildcards at all?
EDIT: here is the html
<select name="tkt-slctr-qty-346[]" id="ticket-selector-tbl-qty-slct-346-1" class="ticket-selector-tbl-qty-slct">
<option value="0"> 0 </option>
<option value="1"> 1 </option>
<option value="2"> 2 </option>
<option value="3"> 3 </option>
<option value="4"> 4 </option>
<option value="5"> 5 </option>
<option value="6"> 6 </option>
<option value="7"> 7 </option>
<option value="8"> 8 </option>
<option value="9"> 9 </option>
<option value="10"> 10 </option>
</select>
Instead of having the id as part of the "name" (which will be used as the key in the $_POST
array, PHP supports using array notation directly:
name="tkt-slctr-qty[346]"
name="tkt-slctr-qty[358]"
You can then iterate over these under a single key:
if (!empty($_POST['tkt-slctr-qty']) && is_array($_POST['tkt-slctr-qty'])) {
foreach ($_POST['tkt-slctr-qty'] as $id => $qty) {
// handle each id/qty value
}
}
If you do have multiple select boxes for each id as well, append []
to each, and create an inner loop:
name="tkt-slctr-qty[346][]"
...
name="tkt-slctr-qty[358][]"
And then handle it in an inner loop:
if (!empty($_POST['tkt-slctr-qty']) && is_array($_POST['tkt-slctr-qty'])) {
foreach ($_POST['tkt-slctr-qty'] as $id => $qtys) {
if (is_array($qtys)) {
foreach ($qtys as $qty) {
// handle each qty if there are multiple fields.
}
}
}
}
You can get post variables to an array then iterate through it while you filter.
foreach($_POST as $key => $value) {
$pos = strpos($key , "tkt-slctr-qty-");
if ($pos === 0){
// do something with $value
}
}
When you submit those arrays, PHP will receive them this way:
$_POST['tkt-slctr-qty-358'][0]
$_POST['tkt-slctr-qty-358'][1]
// ...
If you mean to capture the numbers at the end of the key dynamically, it works the following:
foreach ($_POST as $k => $v) {
if (strpos($k, 'tkt-slctr-qty-') === 0) {
foreach ($v as $innerValue) {
echo 'Key: ' . $k . ' has value: ' . $innerValue . '<br>';
}
}
}
You have to Iterate through the $_POST array holding the collection. Follow the pattern below
$counter = count($_POST['tkt-slctr-qty-346']);
$image = '';
for($i=0; $i< $counter; $i++)
{
$data = $_POST['tkt-slctr-qty-346'][$i];
//Then Write the code that processes the data here
}
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.