Parse query string into an array

Parse query string into an array

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

Parsing Query Strings into Arrays: Handling Edge Cases and Missing Values

Converting a raw query string like pg_id=2&parent_id=2&document&video into a structured array requires more than just splitting on the ampersand delimiter. A naive approach often fails because it assumes every key-value pair is perfectly formed, ignoring the reality of incomplete parameters where a value is absent entirely. In your specific example, you have keys named document and video that appear to be missing their assigned values. The goal is to produce an associative array where these missing keys map to empty strings or null, depending on your downstream logic needs, rather than causing a parsing error or leaving the key out of the result set.

The most robust way to handle this in PHP is using explode combined with str_getcsv or a custom delimiter split, but standard functions like http_build_query work in reverse and don't inherently handle missing values gracefully without post-processing. A common pitfall is relying on parse_str, which by default sets missing values to an empty string. However, if your input string contains keys with no equals sign, parse_str might interpret them differently or require specific configuration. Let's look at a manual parsing strategy that gives you precise control over how those "broken" parameters are treated.

First, we split the string by the ampersand character:

$input = 'pg_id=2&parent_id=2&document&video';
$parts = explode('&', $input);

This yields an array of strings where some contain an equals sign and others do not. Next, we iterate through these parts to separate the key from the value. The logic must check if the = character exists within each part. If it does, we split on the first occurrence only to preserve any potential values containing ampersands (though rare in simple query strings). If the = is missing, we assign an empty string as the default value to match your desired output structure.

$result = [];

foreach ($parts as $part) {
    if (strpos($part, '=') !== false) {
        [$key, $value] = explode('=', $part, 2);
        // Remove URL encoding if necessary before casting
        $result[urldecode(trim($key))] = urldecode(trim($value));
    } else {
        // Handle missing values like 'document' and 'video'
        $result[urldecode(trim($part))] = ''; 
    }
}

In this implementation, we use urldecode to ensure that if the query string contained encoded characters (like %20 for spaces), they are resolved correctly. We also trim whitespace around keys and values, which is a frequent source of bugs when comparing array contents later. The final structure will be:

array(
    'pg_id' => '2',
    'parent_id' => '2',
    'document' => '',
    'video' => ''
)

Note that the numeric values are currently strings. If your application requires integers for pg_id and parent_id, you must cast them explicitly:

$result['pg_id'] = (int)$result['pg_id'];
$result['parent_id'] = (int)$result['parent_id'];

This distinction is critical. In many frameworks, passing a string "2" where an integer 2 is expected can lead to silent failures in logic gates or SQL queries that rely on type coercion. By handling the casting immediately after parsing, you ensure data integrity from the moment it enters your system.

If you are already using the Laravel framework, you might find yourself reaching for request()->query(), but that helper expects a fully formed URL string passed to the constructor. Manually constructing the array from a raw string is less common in modern Laravel apps but remains necessary when processing logs, legacy data imports, or custom form submissions where the query string is embedded directly in a payload rather than being part of the HTTP request. For those scenarios, understanding how to parse the delimiters and handle the absence of values ensures your application behaves predictably regardless of how the client sends the data.

Our network