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. Here is an example:
<?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 the separator between the key-value pairs in the query string. The default separator is &
.
<?php
$query_array = [
"key1" => "value1",
"key2" => "value2",
"key3" => "value3",
];
$query_string = http_build_query($query_array, "&");
echo $query_string;
This will output the same string as before.
<?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
.