How to create a query string from an array in PHP

  279 views   5 months ago PHP

When sending get request to third party server, you need to add query string of data into url. Some request accept request to text format, means you need to pass data into url query string. You may already have PHP array or object which you want to pass as payload. In this situation, you need to convert array or object into query string.

In this article, we will show you how you can convert array into query string. PHP has built-in function http_build_query which convert array or object into URL-encoded query string.

Syntax:

http_build_query($data, $numeric_prefix, $separator, $encoding);

Parameters:

$data required array or object which you want to convert
$numeric_prefix optional string prefix on numeric key
$separator optional parameter seperator instead of default &
$encoding optional encoding type default PHP_QUERY_RFC1738

Example:

<?php

$user = [
    'name' => 'Harsukh Makwana',
    'email' => '[email protected]',
    'twitter' => 'harsukh21',
    'github' => 'harsukh21'
];

$data = http_build_query($user);

echo($data); // name=Harsukh+Makwana&email=harsukh21%40gmail.com&twitter=harsukh21&github=harsukh21

If you need indexed array to be query string with prefixed or comma seperated string, here is the example:

<?php

$user = [
    '1' => 'Harsukh Makwana',
    '2' => '[email protected]',
    '3' => 'harsukh21',
    '4' => 'harsukh21'
];

$data = http_build_query($user, 'param_', ',');

echo($data); // param_1=Harsukh+Makwana,param_2=harsukh21%40gmail.com,param_3=harsukh21,param_4=harsukh21

If you want to use your own custom logic or working on PHP 4, here is the custom function to do same result as above:

<?php

$user = [
    'name' => 'Harsukh Makwana',
    'email' => '[email protected]',
    'twitter' => 'harsukh21',
    'github' => 'harsukh21'
];

/**
 * Builds an http query string
 * 
 * @param array
 * @return string
 */
function httpbuildQuery($query, $seperator = '&') {

    $query_array = [];

    foreach($query as $key => $key_value) {
        $query_array[] = urlencode($key) . '=' . urlencode($key_value);
    }

    return implode($seperator, $query_array);
}

$data = httpbuildQuery($user);

echo($data); // name=Harsukh+Makwana&email=harsukh21%40gmail.com&twitter=harsukh21&github=harsukh21

I hope it will help you.

Author : Harsukh Makwana
Harsukh Makwana

Hi, My name is Harsukh Makwana. i have been work with many programming language like php, python, javascript, node, react, anguler, etc.. since last 5 year. if you have any issue or want me hire then contact me on [email protected]