Skip to main content
Drupal API
User account menu
  • Log in

Breadcrumb

  1. Drupal Core 11.1.x
  2. Query.php

function Query::build

Build a query string from an array of key value pairs.

This function can use the return value of `parse()` to build a query string. This function does not modify the provided keys when an array is encountered (like `http_build_query()` would).

Parameters

array $params Query string parameters.:

int|false $encoding Set to false to not encode,: PHP_QUERY_RFC3986 to encode using RFC3986, or PHP_QUERY_RFC1738 to encode using RFC1738.

bool $treatBoolsAsInts Set to true to encode as 0/1, and: false as false/true.

File

vendor/guzzlehttp/psr7/src/Query.php, line 74

Class

Query

Namespace

GuzzleHttp\Psr7

Code

public static function build(array $params, $encoding = PHP_QUERY_RFC3986, bool $treatBoolsAsInts = true) : string {
    if (!$params) {
        return '';
    }
    if ($encoding === false) {
        $encoder = function (string $str) : string {
            return $str;
        };
    }
    elseif ($encoding === PHP_QUERY_RFC3986) {
        $encoder = 'rawurlencode';
    }
    elseif ($encoding === PHP_QUERY_RFC1738) {
        $encoder = 'urlencode';
    }
    else {
        throw new \InvalidArgumentException('Invalid type');
    }
    $castBool = $treatBoolsAsInts ? static function ($v) {
        return (int) $v;
    } : static function ($v) {
        return $v ? 'true' : 'false';
    };
    $qs = '';
    foreach ($params as $k => $v) {
        $k = $encoder((string) $k);
        if (!is_array($v)) {
            $qs .= $k;
            $v = is_bool($v) ? $castBool($v) : $v;
            if ($v !== null) {
                $qs .= '=' . $encoder((string) $v);
            }
            $qs .= '&';
        }
        else {
            foreach ($v as $vv) {
                $qs .= $k;
                $vv = is_bool($vv) ? $castBool($vv) : $vv;
                if ($vv !== null) {
                    $qs .= '=' . $encoder((string) $vv);
                }
                $qs .= '&';
            }
        }
    }
    return $qs ? (string) substr($qs, 0, -1) : '';
}

API Navigation

  • Drupal Core 11.1.x
  • Topics
  • Classes
  • Functions
  • Constants
  • Globals
  • Files
  • Namespaces
  • Deprecated
  • Services
RSS feed
Powered by Drupal