Search code examples
phpforeachgetkey-value

PHP Fetch Name and Value FROM $_GET


I'm trying to convert a simple if/elseif conditional to a case conditional and only a single $_GET value is being passed at a time via an img src link so is the foreach loop necessary and/or does the case conditional actually need to be inside the loop? Otherwise how to I retrieve the key name and value from the $_GET?

if (isset($_GET)) :
    foreach ($_GET as $GETkey=>$GETvalue):
        switch ($GETkey):
            case "AuthorID":
                $Year = date("Y");
                $AuthorName = DBLookup("SELECT `AuthorName` FROM authorbiographies WHERE `ID`=$GETvalue",$siteDB);
                $String = "Copyright © $Year\n$AuthorName";
                $FontSize = 10;
                $Angle = 0;
            break;
            case "CategoryID":
                $String = DBLookup("SELECT `CategoryName` FROM categories WHERE `ID`=$GETvalue",$siteDB);
                $FontSize = 15;
                $Angle = 0;
            break;
            case "Splash":
                $String = urldecode($GETvalue);
                $FontSize = 38;
                $Angle = 0;
            break;
        endswitch;
    endforeach;
endif;

It is being called using:

 <img src="/internals/viewers/show_logo.php?AuthorID=1">

or

 <img src="/internals/viewers/show_logo.php?CategoryID=1">

for example.


Solution

  • You can use the key() and current() functions to get the current key and value of an array.

    For an array with a single element, this will return the first and only key and value. There's no need for a loop.

    $GETkey = key($_GET);
    $GETvalue = current($_GET);
    switch ($GETkey) {
        ...
    }