Search code examples
phpif-statementparametersgetisset

Check if only one GET Parameter is Defined?


I have some code, essentially containing a page-specific header, that should only load if only one GET parameter is defined in my URL.

For example, if I want the header only to show if "thisonly" parameter in the URL is set, if the URL was:

http://www.example.com?thisonly=w&thisone=q&thistwo=q&thisthree=q

Previously I have been using this code to check:

    if((isset($_GET[thisonly])) && (!isset($_GET[thisone])) && (!isset($_GET[thistwo])) && (!isset($_GET[thisthree]))) {
    // Run this code
    }

In the case above, the code would not run, since those other parameters are set.

However, this will be a hassle to update, especially if I end up adding more parameters, and will have to go back and add to this code to make sure they also are not set.

Is there some way to shorten it down to the equivalent of

    if((isset($_GET[thisonly])) && (!isset($_GET[nothingelse]))) {
    // Run this code
    }

E.g., if "thisonly" is the only parameter set, and no other parameters are set, then run the code?

Any help appreciated -- thanks!


Solution

  • if(count($_GET) === 1 && isset($_GET['thisonly'])) {
    

    This checks to see if $_GET is an array with only one element and it is $_GET['thisonly'].