简体   繁体   中英

how to get Value AND ID from a checkbox in a loop using php?

I am trying to get the values and ID's of all checked checkboxes after a submit.
The loop I have now works and retrieves all checked checkboxes, and I can do an echo of all there values.
But I also need to get the ID at the same time, how can I do that ?

I found many answers here but they all only retrieve the Value and never the ID, I need them both.

My checkboxes are setup like this :

<input type="checkbox" name="cbTrucks[]" value="1778" id="HT1234">
<input type="checkbox" name="cbTrucks[]" value="1946" id="HT4567">
<input type="checkbox" name="cbTrucks[]" value="1609" id="HT9876">

and my current loop is this :

$values = "";
if (!empty($_POST['cbTrucks'])) 
{
    foreach($_POST['cbTrucks'] as $checkbox) 
    {
        if ($values == "")
            $values = $checkbox;
        else
            $values = $values.",".$checkbox;
    }

    echo $values;
}
else
{
    echo "filter is empty";
}

This display the values of all selected checkboxes, but I also wont the ID's

Something like

$values = "";
$ids = "";
if (!empty($_POST['cbTrucks'])) 
{
    foreach($_POST['cbTrucks'] as $checkbox) 
    {
        if ($values == "")
            $values = $checkbox;
        else
            $values = $values.",".$checkbox;

        $ids = $ids.$checkbox.id; // I need something like this
    }

    echo $values;
}

You can't, because IDs are not submitted in POST by default. What I suggest is that you add the IDs to the values as follows:

<input type="checkbox" name="cbTrucks[]" value="1778_HT1234">
<input type="checkbox" name="cbTrucks[]" value="1946_HT4567">
<input type="checkbox" name="cbTrucks[]" value="1609_HT9876">

Then use in PHP:

list($value, $id) = explode('_', $checkbox);

In the loop:

foreach($_POST['cbTrucks'] as $checkbox) {
   list($value, $id) = explode('_', $checkbox);
}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM