phparraysquery-stringassociative-arraystring-parsing

Parse and sanitize a (URL) querystring into an associative array


I need some help writing a code that creates an array in the format I needed in. I have this long string of text like this -> "settings=2&options=3&color=3&action=save"...etc Now the next thing I did to make it into an array is the following:

$form_data = explode("&", $form_data);

Ok so far so good...I now have an array like so:

Array
(
[0] => settings=2
[1] => options=3
[2] => color=3
[3] => action=save
)
1

Ok now I need to know how to do two things. First, how can I remove all occurences of "action=save" from the array?

Second, how can I make this array become a key value pair (associative array)? Like "settings=>2"?


Solution

  • There's a function for that. :)

    parse_str('settings=2&options=3&color=3&action=save', $arr);
    if (isset($arr['action']) && $arr['action'] == 'save') {
        unset($arr['action']);
    }
    print_r($arr);
    

    But just for reference, you could do it manually like this:

    $str = 'settings=2&options=3&color=3&action=save';
    $arr = array();
    foreach (explode('&', $str) as $part) {
        list($key, $value) = explode('=', $part, 2);
        if ($key == 'action' && $value == 'save') {
            continue;
        }
        $arr[$key] = $value;
    }
    

    This is not quite equivalent to parse_str, since key[] keys wouldn't be parsed correctly. I'd be sufficient for your example though.