Search code examples
phparrayscollisionform-submitquerystringparameter

Parse form submission data from query string / jQuery.serialize() containing duplicate keys without losing values


I am trying to figure out how I can handle possible duplicate array keys.

I have this form with a select dropdown which can select multiple options (more than 1). And I am using jQuery.serialize() to serialize the form on submit.

The serialized string for a multi-select element would look like so:

select=1&select=2&select=3 // assuming I selected first 3 options.

Now in the PHP side, I have the following code to handle the "saving" part into a database.

$form_data = $_POST['form_items'];

$form_data = str_replace('&','####',$form_data);
$form_data = urldecode($form_data);
$arr = array();
foreach (explode('####', $form_data) as $part) {
    list($key, $value) = explode('=', $part, 2);
    $arr[$key] = $value;
}

This all works for the rest of the form elements, but when it comes to the select element, it only picks the last selected key/value pair. So my array now looks like this:

Array ( [select_element] => 3)

What I need, is for it to look like:

Array ( [select_element] => '1,2,3')

So I guess what I am asking is based on my code, how can I check if a key already exists and if it does, append to the $value.


Solution

  • Ok, I was able to resolve this issue by using the following code:

        if (array_key_exists($key, $arr)) {
            $arr[$key] = $arr[$key].','.$value;
        } else { 
            $arr[$key] = $value;
        }
    

    So now the loop looks like this:

    foreach (explode('####', $form_data) as $part) {
        list($key, $value) = explode('=', $part, 2);
    
        if (array_key_exists($key, $arr)) {
            $arr[$key] = $arr[$key].','.$value;
        } else { 
            $arr[$key] = $value;
        }
    }
    

    This will essentially string up the value together separated by a comma which can then be exploded out into an array later.