web analytics

How to get variable value from URL query string in PHP?

We already know that we can get URL query string variable in $_GET super global array. But sometimes we might have to analyze a string which is an URL with query string and need to pull out value of a given variable from that. Also, it can be that we were given only the query part of an URL as string and we have to find out value of a given variable. Lets see how we can face this issue.

Get variable’s value from URL with query string in PHP:

$url = 'http://onlineclassnotes.com?part=3&m=1&referrer=google_search';
$parts = parse_url($url);
$values = array();
parse_str($parts['query'],$values);
echo $values['part'];

So what we are doing here is, that we are using parse_url() function first that is cutting out various parts of the $url as follows,

Array
(
[scheme] => http
[host] => onlineclassnotes.com
[query] => part=3&m=1&referrer=google_search
)
Among these parts, what is our concern is $parts[‘query’] which is having the query part of the $url.
Okay, then we are cutting down the $parts[‘query’] using the parse_str() function, where we are giving the query part as the first parameter and the array to store all the variable and values. Thus we are getting the $values array filled up with variable and values from query string of the URL. Following is the output of the $values array.

Array
(
[part] => 3
[m] => 1
[referrer] => google_search
)

Get variable’s value from string like the query part of an URL in PHP:

Consider the following example

$url = 'part=3&m=1&referrer=google_search';
$values = array();
parse_str($url,$values);
echo $values['part'];

As this time, the $url is itself the query part of an URL, we do not need the parse_url() function anymore to find the query part of the string, so we can simply skip to the parse_str() function to get the desired output.

Array
(
[part] => 3
[m] => 1
[referrer] => google_search
)

Now from the $values, we can get value of any variable directly. Cheers.

Thank you. Take a moment to share 🙏