1

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
Kirk Ross
  • 6,413
  • 13
  • 61
  • 104
  • 1
    your URLs are so varied how can you be sure there will never be a second param? you should conform to `site.com/page/foobar`, then you can be sure the controller is page and the action is foobar – Lawrence Cherone Oct 24 '21 at 00:29

3 Answers3

2

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.

Decent Dabbler
  • 22,532
  • 8
  • 74
  • 106
1

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

Just use an if statement

if(empty($_GET)) {
    continue
}
dlystyr
  • 103
  • 6
1
<?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

sukalogika
  • 603
  • 4
  • 11
  • 18
  • Thank you kindly, that totally works. Do you have a tip / article link for implementing a vanilla PHP MVC where I can replace `site.com/venues/?venue=venue-name` with `site.com/venues/venue-name` and not have to create directories with index pages in each? – Kirk Ross Oct 24 '21 at 02:19
  • https://stackoverflow.com/questions/28168375/how-to-write-htaccess-rewrite-rule-for-seo-friendly-url – sukalogika Oct 24 '21 at 03:03