How to get a parameter from a URL string in PHP

I don’t know about you but I often need to get an individual $_GET parameter from a URL string in PHP.

Here’s a quick method that you can use to get a single parameter from a string url:

function getUrlParam($url, $key)
{
    $params = array();
    parse_str(parse_url($url, PHP_URL_QUERY), $params);
    return isset($params[$key]) ? $params[$key] : null;
}

To use this function simply pass the url string and the key that you want to extract, e.g.

echo getUrlParam('http://www.example.com/?name=John&age=25', 'name');

This will output the value of the parameter:

John

I hope this saves you a bit of time!