Search code examples
phpif-statementquery-stringisset

PHP: similar functionality of a jQuery $(this)?


I have a page where I can pass from one to three variables through the query string.

There are three cases:

  • products.php?page=x
  • products.php?gender=x&page=x
  • products.php?gender=x&FILTER=x&page=x

The variables page and gender are always named like this, but the FILTER one can be three different things: brand, category and subcategory.

Because the gender variable is optional, I cannot use $_SERVER['QUERY_STRING'] to get its name and value value because it's not always the second variable.

Based on the FILTER selected I do different things, each filter has a different functionality attached to it.

My question is: how can I know which of the three filters is selected after excluding page and gender, so basically if something like this is possible

if ( isset($_GET['brand']) || isset($_GET['category']) || isset($_GET['subcategory']) ) {

    // $selected = whichever variable is set, something like $(this) in jQuery

}

The alternative is to create an if() statement for each of the three cases, but if I will add more filters then I will have to add more if() statements.


Solution

  • 1) You could use if statements just like you said.

    2) You could do something like

    products.php?gender=x&filter=x+c&page=x

    $filter = explode('+', $_GET['filter']));
    $type = $filter[0] //x
    $value = $filter[1] //c
    

    Then you could use a switch for more readabilty

    switch($type){
        case 'brand':
            //do stuff
            break;
        default:
            //do stuff
    }