PHP

Convert Array to URL Query String and Back

Master the conversion of PHP arrays into URL-friendly query strings using `http_build_query` and then efficiently parse them back into an array with `parse_str` for web parameters.

<?php
$params = [
    'name' => 'John Doe',
    'age' => 30,
    'city' => 'New York',
    'tags' => ['php', 'web']
];

// Convert array to URL query string
$queryString = http_build_query($params);
echo "Query String: " . $queryString . "
";
// Expected output: Query String: name=John+Doe&age=30&city=New+York&tags%5B0%5D=php&tags%5B1%5D=web

// Parse query string back to array
$parsedParams = [];
parse_str($queryString, $parsedParams);

print_r($parsedParams);
// Expected output:
// Array
// (
//     [name] => John Doe
//     [age] => 30
//     [city] => New York
//     [tags] => Array
//         (
//             [0] => php
//             [1] => web
//         )
// )
?>
How it works: `http_build_query()` is invaluable for converting an associative array into a URL-encoded query string, perfect for generating URLs, API requests, or redirects. Conversely, `parse_str()` takes a query string and parses it into an associative array. This pair of functions is fundamental for handling dynamic web parameters, making it easy to serialize and deserialize data for browser communication.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs