PHP

Convert Associative Array to URL Query String

Generate a properly formatted URL query string from an associative array of parameters, perfect for building dynamic URLs in web applications.

$params = [
    'page' => 1,
    'category' => 'electronics',
    'sort_by' => 'price_asc',
    'filters' => [
        'brand' => 'samsung',
        'rating' => 4
    ],
    'search' => 'laptop charger'
];

$queryString = http_build_query($params);
echo "Generated Query String:
" . $queryString . "
";
// Expected: page=1&category=electronics&sort_by=price_asc&filters%5Bbrand%5D=samsung&filters%5Brating%5D=4&search=laptop+charger

// Example with URL prefix
$baseUrl = "https://example.com/products";
$fullUrl = $baseUrl . '?' . $queryString;
echo "Full URL:
" . $fullUrl . "
";
How it works: The `http_build_query()` function is indispensable for web developers. It takes an associative array of key-value pairs and converts it into a URL-encoded query string suitable for appending to a URL. It correctly handles nested arrays, encoding them with square brackets (`[]`) for parameter names, and properly encodes special characters, ensuring the generated string is safe for URLs.

Need help integrating this into your project?

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

Hire DigitalCodeLabs