Dimitris Damilos
Dimitris Damilos

Reputation: 2438

$_POST and variable indexes

I have a project where I create hidden input values with jQuery. These represent groups and members so I have one array for the groups themselves and arrays with the members of each groups.

For example after a few creations the code in the form includes

<input type="hidden" name="groups['group_2']" value="0">
<input type="hidden" name="groups['group_1']" value="0">
<input type="hidden" class="mem_id_holder" name="group_1[]" value="FWNGVISkjW">
<input type="hidden" class="mem_id_holder" name="group_1[]" value="G0t9E3C0yG">
<input type="hidden" class="mem_id_holder" name="group_2[]" value="NT-JEDVCS9">

for an example of 2 groups with 2 members in group_1 and 1 member in group_2.

Now, after the submit my code to iterate through the values I use this code:

if ($groups_no && isset($_POST['groups']) && !empty($_POST['groups'])){
    $groups = $_POST['groups'];
    foreach ($groups as $key => $val){
        if (isset($_POST[$key]) && !empty($_POST[$key])){
            $group_members = $_POST[$key];      
            foreach ($group_members as $member_key => $member_val){
                echo 'Actions to be done here!';
            }
        }
    }
}

The problem I have is that I get the following warning and the program fails:

Notice: Undefined index: 'group_1' in C:\ ... .php on line 31
Warning: Invalid argument supplied for foreach() ...
Notice: Undefined index: 'group_2' in C:\ ... .php on line 31
Warning: Invalid argument supplied for foreach() ...

When I use $_POST['group_1'] everything works fine but since I do not know how many and which groups I will have to insert I need the variable. I have tried some different things suggested via some Google results but nothing worked.

Any ideas? Is $_POST even capable of having variables as indexes? Also if it isn't, is there any other workaround?

Upvotes: 0

Views: 105

Answers (2)

Ian Jamieson
Ian Jamieson

Reputation: 4826

By doing this:

<input type="hidden" class="mem_id_holder" name="group_1[]" value="FWNGVISkjW">

Instead of this:

<input type="hidden" class="mem_id_holder" name="group_1" value="FWNGVISkjW">

When you post the values you are going to get an array, so $_POST['group_1'] would not exist as a string in the first instance, it would be $_POST['group_1'][0]. So you would have to iterate through that value as well.

Hope this helps.

Upvotes: 0

gen_Eric
gen_Eric

Reputation: 227310

In your HTML, don't put quotes around the array indexes.

<input type="hidden" name="groups[group_2]" value="0">
<input type="hidden" name="groups[group_1]" value="0">
<input type="hidden" class="mem_id_holder" name="group_1[]" value="FWNGVISkjW">
<input type="hidden" class="mem_id_holder" name="group_1[]" value="G0t9E3C0yG">
<input type="hidden" class="mem_id_holder" name="group_2[]" value="NT-JEDVCS9">

Upvotes: 2

Related Questions