How to Pass an Array in URL Query String with PHP

PHP includes the http_build_query() method for creating URL encoded query string. This method is available only on PHP 5 and above versions. In this snippet, you will learn how to pass an array in URL query string using PHP.

The syntax of http_build_query() will look as follows:

http_build_query($query, $numeric_prefix, $separator, $encoded_type)

Watch a course Learn object oriented PHP

Passing a Simple Array within http_build_query()

In this section, we are going to use $vars array for generating the URL query string. The $vars array includes the data of search keyword, as well as the page number.

Let’s see an example where this array is passed to the http_build_query() method for generating a query string:

<?php

$vars = ['page' => 26, 'search' => 'w3docs'];
$qs = http_build_query($vars);
$url = 'http://www.example.com/search.php?' . $qs;
echo $url;

?>

The code, represented above will return the following url query string:

http://www.example.com/search.php?page=26&search=w3docs

Passing an Indexed Array within http_build_query()

Now, let’s see an example where $vars is an indexed array that comprises an employee data:

<?php

$vars = ['employee', 'brown', 'developer', 'emp_id' => '332'];
$qs = http_build_query($vars);
$url = 'http://www.example.com/search.php?' . $qs;
echo $url;

?>

The code above will return the following url query string:

http://www.example.com/search.php?0=employee&1=brown&2=developer&emp_id=332

Passing a Multidimensional Array within http_build_query()

In this section, we will consider $vars as a multidimensional array with employee data. Once passing through the http_build_query() method, it will return a complex url query string.

Here is an example:

<?php

$vars = ['employee' => ['name' => 'Brown', 'age' => 41, 'dept' => 'IT', 'dob' => '9/22/1980'], 'role' => ['engineer', 'developer']];
$qs = http_build_query($vars);
$url = 'http://www.example.com/search.php?' . $qs;
echo $url;

?>

This code will return the following url query string:

http://www.example.com/search.php?employee%5Bname%5D=Brown&employee%5Bage%5D=39&employee%5Bdept%5D=IT&employee%5Bdob%5D=9%2F22%2F1980&role%5B0%5D=engineer&role%5B1%5D=developer

Describing Query String

The query string term is considered a part of Uniform Resource Locator (URL). It is in the form of a series of key-value pairs. Generally, it is used for creating a typical url or getting data from URL.

So, you can use the query string for different purposes such as search keywords, url building, specific web page tracking, and many more.