Home > Mobile >  PHP - get URL param with or without key
PHP - get URL param with or without key

Time:10-24

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

CodePudding user response:

Here's my solution:

$slug = $_GET['slug'] ?? reset(array_keys($_GET));

var_dump($slug);

It will return the first parameter name when slug is not found.

Be aware that it will be an empty string when the URL parameter 'slug' has no value, i.e.: ?slug and false if no parameter is found at all.

Perhaps this is a little more consistent:

// edit: added redundant parentheses to make operator precedence more clear
$slug = ($_GET['slug'] ?? reset(array_keys($_GET))) ?: null;

var_dump($slug);

...as it will return null for both previously mentioned edge cases.

CodePudding user response:

$_GET is actually an array that holds all of that information.

Just use an if statement

if(empty($_GET)) {
    continue
}

CodePudding user response:

<?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

  • Related