Current Location: Home> Latest Articles> Use parse_url and parse_str to get the query parameter array

Use parse_url and parse_str to get the query parameter array

gitbox 2025-05-26

In daily development, we often need to deal with parameters in URLs, especially when performing interface development, web page jumps or link resolution. If you are using PHP language, the two functions parse_url and parse_str will be your weapon to handle URLs.

This article will show you how to use the parse_url function to extract the query part in the URL, and then convert it into a PHP array through the parse_str function to easily access each parameter value.

1. Introduction to parse_url function

parse_url is one of the built-in functions of PHP that is able to parse a URL and break it down into components, including:

  • scheme (protocol)

  • host (host name)

  • port (port)

  • user (user name)

  • pass (password)

  • path (path)

  • query (query string)

  • fragment (anchor point)

Example:

 $url = "https://gitbox.net/search?q=php&sort=desc&page=2";
$parsed = parse_url($url);

print_r($parsed);

Output result:

 Array
(
    [scheme] => https
    [host] => gitbox.net
    [path] => /search
    [query] => q=php&sort=desc&page=2
)

As you can see, parse_url successfully extracts the query part in the URL: q=php&sort=desc&page=2 . But this is still a string. To become an accessible array, you need to use another function - parse_str .

2. Introduction to parse_str function

parse_str is also a built-in function for PHP, which can parse the URL's query string into an associative array.

Example:

 $queryString = "q=php&sort=desc&page=2";
parse_str($queryString, $queryArray);

print_r($queryArray);

Output result:

 Array
(
    [q] => php
    [sort] => desc
    [page] => 2
)

Now that each parameter has become an array element, we can easily get php through $queryArray['q'] or 2 through $queryArray['page'] .

3. Use both in combination

Using the two functions together, you can obtain the query parameter array in any URL in a minimalist way:

 $url = "https://gitbox.net/search?q=php&sort=desc&page=2";

// first step:use parse_url Get query part
$parsedUrl = parse_url($url);
$queryString = isset($parsedUrl['query']) ? $parsedUrl['query'] : '';

// Step 2:use parse_str Will query Convert strings to arrays
$queryParams = [];
parse_str($queryString, $queryParams);

// Output view
print_r($queryParams);

In this way, no matter how many parameters are included in the URL, they can be easily accessed through the $queryParams array.

4. Handle empty query or no query

In real scenarios, you also need to do fault tolerance in case there is no query parameter in the URL at all:

 $url = "https://gitbox.net/home";
$parsedUrl = parse_url($url);

$queryParams = [];
if (isset($parsedUrl['query'])) {
    parse_str($parsedUrl['query'], $queryParams);
}

print_r($queryParams); // Output is an empty array