Skip to content
Advertisement

PHP – get URL param with or without key

I know how to do this in a clunky verbose way, but is there an elegant way to retrieve a single param from a URL whether or not there is a key or index page in the URL? i.e. there will never be a &secondparam=blah.

$_GET["slug"] only works if the url has slug=foobar

E.g. return foobar for any of these URLs

site.com/page/index.php?slug=foobar

site.com/page/index.php?foobar

site.com/page/?slug=foobar

site.com/page/?foobar

Advertisement

Answer

<?php

function reader()
{
    foreach($_GET as $key => $val)
    {
        if( ! empty($val))
        {
            return $val;
        }
        return $key;
    }
}

echo reader();
?>

Explaination: return $value first. If not empty, return that $key

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement