W3docs

PHP function to build query string from array

In PHP, you can use the http_build_query function to create a URL encoded query string from an array.

In PHP, you can use the http_build_query function to create a URL encoded query string from an array. Here is an example:

Example of using the http_build_query() function to create a URL encoded query string from an array in PHP

<?php

$query_array = [
  "key1" => "value1",
  "key2" => "value2",
  "key3" => "value3",
];

$query_string = http_build_query($query_array);
echo $query_string;

This will output a string like key1=value1&key2=value2&key3=value3.

You can also pass a second argument to http_build_query to specify a prefix for numeric array keys. The third argument specifies the separator between key-value pairs, which defaults to &. For stricter URL encoding standards, you can use the fourth argument PHP_QUERY_RFC3986.

Example of using the http_build_query() function to specify a prefix for numeric array keys in PHP

<?php

$query_array = [
  "key1" => "value1",
  0 => "value2",
  1 => "value3",
];
$query_string = http_build_query($query_array, "item_");
echo $query_string;

This will output key1=value1&item_0=value2&item_1=value3.

Example of a PHP function to build query string from array

<?php

$query_array = [
  "key1" => "value1",
  "key2" => "value2",
  "key3" => "value3",
];

// Set the separator character to ";"
$query_string = http_build_query($query_array, "", ";");

echo $query_string;
// Output: key1=value1;key2=value2;key3=value3

This will output a string like key1=value1;key2=value2;key3=value3.