In PHP, the parse_str() function is a built-in utility designed to parse query strings into variables. It’s commonly used to extract parameters from URLs or emulate data structures from form submissions. This function can handle both simple key-value pairs and more complex array-style parameters, making it especially useful in web applications.
bool parse_str(string $str [, array &$arr])
The function takes a query string $str and an optional reference variable &$arr to store the parsed output. If the second argument is provided, all parsed variables are placed into that array rather than being injected into the current scope.
Here's an example of parsing a standard query string:
$query = "name=John&age=25&country=USA";
parse_str($query, $params);
echo $params['name']; // Outputs "John"
echo $params['age']; // Outputs "25"
echo $params['country']; // Outputs "USA"
In this example, $query contains a properly formatted URL query string. parse_str() parses it into an associative array, making the data easy to access.
When a query string includes array-style syntax (e.g., age[]=25&age[]=26), parse_str() will automatically convert those into PHP arrays:
$query = "name=John&age[]=25&age[]=26&country=USA";
parse_str($query, $params);
echo $params['name']; // Outputs "John"
print_r($params['age']); // Outputs Array ( [0] => 25 [1] => 26 )
echo $params['country']; // Outputs "USA"
This is particularly useful for processing multi-select fields or checkboxes in forms where multiple values are submitted under the same key.
Although parse_str() is typically used for URL-style strings, it can also be used to parse strings formatted like cookies, as long as the delimiter is an ampersand (&) instead of a semicolon (;):
$cookie = "name=John&age=25&country=USA";
parse_str($cookie, $params);
echo $params['name']; // Outputs "John"
echo $params['age']; // Outputs "25"
echo $params['country']; // Outputs "USA"
The parse_str() function is a powerful and efficient tool in PHP for breaking down query strings, form data, and cookie-like strings into structured arrays or variables. By understanding its behavior and recommended usage, developers can securely and effectively manage incoming data from HTTP requests.