PHP http_build_query Function: Usage, Parameters, and Examples

This article explains the PHP http_build_query function, detailing its purpose of generating URL‑encoded query strings from arrays or objects, describing each parameter (query_data, numeric_prefix, arg_separator, enc_type), the return value, and providing multiple code examples illustrating typical usage and output.

Laravel Tech Community
Laravel Tech Community
Laravel Tech Community
PHP http_build_query Function: Usage, Parameters, and Examples

The http_build_query function in PHP creates a URL‑encoded query string from a given array or object, which can then be appended to a URL for HTTP requests.

Parameters : query_data – an array or object (public properties only) that provides the data to be encoded. It may be a simple one‑dimensional array or a nested array structure. numeric_prefix – a string prefixed to numeric indices when the base array contains numeric keys, ensuring valid variable names after decoding. arg_separator – the separator used between arguments; defaults to the value of arg_separator.output if not supplied. enc_type – encoding type, default PHP_QUERY_RFC1738 (spaces become "+"), or PHP_QUERY_RFC3986 (spaces become "%20").

Return value : a URL‑encoded string representing the supplied data.

Example 1 – basic usage:

<?php
$data = array(
    'foo' => 'bar',
    'baz' => 'boom',
    'cow' => 'milk',
    'php' => 'hypertext processor'
);

echo http_build_query($data) . "
";
?>

Output:

foo=bar&baz=boom&cow=milk&php=hypertext+processor

Example 2 – using a numeric prefix:

<?php
$data = array('foo', 'bar', 'baz', 'boom', 'cow' => 'milk', 'php' => 'hypertext processor');

echo http_build_query($data, 'myvar_') . "
";
?>

Output:

myvar_0=foo&myvar_1=bar&myvar_2=baz&myvar_3=boom&cow=milk&php=hypertext+processor

These examples demonstrate how http_build_query can be customized with different separators and prefixes to produce query strings suitable for various web applications.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

BackendWeb DevelopmentPHPURL encodinghttp_build_query
Laravel Tech Community
Written by

Laravel Tech Community

Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.