In PHP development, it is common to handle conversions between URL query strings and arrays. For example, data submitted via front-end forms is passed to the back-end as a query string, which often needs to be converted into an array for processing. Conversely, when building URLs, arrays need to be converted back into query strings.
PHP provides us with two very convenient functions: http_build_query and parse_str, to achieve this functionality.
The http_build_query function can convert an array into a URL-encoded query string. It is commonly used to construct parameters for GET requests.
string http_build_query(array $data, string $numeric_prefix = "", ?</span>string $arg_separator = null</span>, </span>int $encoding_type = PHP_QUERY_RFC1738)
</span>
$params = [
'name' => 'Zhang San',
'age' => 25,
'hobbies' => ['reading', 'coding']
];
<p>$queryString = http_build_query($params);<br>
echo $queryString;<br>
</span>
name=%E5%BC%A00%E4%B8%89&age=25&hobbies%5B0%5D=reading&hobbies%5B1%5D=coding
Note: By default, arrays are serialized with indexes, such as hobbies[0]=reading&hobbies[1]=coding.
If you need to customize the separator or encoding method, you can use additional parameters. For example, changing the separator to a semicolon:
echo http_build_query($params, "", ";");
Output:
name=%E5%BC%A00%E4%B8%89;age=25;hobbies%5B0%5D=reading;hobbies%5B1%5D=coding
The parse_str function parses a URL query string into an array or variables, often used to parse GET requests or custom strings.
void parse_str(string $string, array &$result)
</span></span>
$query = 'name=%E5%BC%A0%E4%B8%89&age=25&hobbies%5B0%5D=reading&hobbies%5B1%5D=coding';
parse_str($query, $output);
</span>
print_r($output);
</span>
Array
(
[name] => Zhang San
[age] => 25
[hobbies] => Array
(
[0] => reading
[1] => coding
)
)
Note: By default, parse_str assigns variables in the current scope. If the second argument is not provided, variables appear as individual variables in the current scope, which may cause variable overwrites in some cases. Therefore, it is recommended to always provide the second argument as the target array.
Simulating Front-end Forms: Convert arrays into query strings to simulate GET requests.
URL Rewriting and Redirection: Construct parameters when generating dynamic URLs.
API Requests: Concatenate parameters when sending API requests.
Parameter Debugging Tools: Used for building parameter strings or parsing debug responses.
With http_build_query and parse_str, we can easily convert between arrays and URL query strings. These two functions are not only simple and easy to use but also powerful tools essential for parameter handling in everyday PHP development. Mastering them can greatly improve our efficiency in managing URL and data interactions.