0

I understand I can use the following to see if the parameter p exists in the URL. However this will also work if there is also a q, t, r etc parameter

if(isset($_GET['p'])) {}

I also know that the following sees if there is any parameter set

if(count($_GET)) {}

However what i need is:

If ONLY parameter p exists -> do something... else if parameter p exists and any other parameter exists else do something... else if parameter != p , or no parameter exists - do something else

Any tips would be much appreciated

4 Answers 4

1
if(isset($_GET['p']) && count($_GET['p']) == 1){
//do something
} else if (isset($_GET['p'])){
//do something
} else {
//do something else
}
Sign up to request clarification or add additional context in comments.

Comments

0

This is apparently what you are looking for:

<?php
// ...
if ((count($_GET) === 1) && isset($_GET['p'])) {
  // GET argument 'p' exists and is the only one
} elseif (isset($_GET['p']) {
  // GET argument'p' exists
} else{
  // GET argument'p' does _not_ exist
} 

Comments

0
$wantedKeys = ['p'];

if (array_diff_key($_GET, array_flip($wantedKeys))) {
    echo 'keys other than ', join(', ', $wantedKeys), ' are in $_GET';
}

This scales up to any number of wanted keys.
In combination with "needs all and none other":

if (
    count(array_intersect_key($_GET, array_flip($wantedKeys))) == count($wantedKeys)
    && !array_diff_key($_GET, array_flip($wantedKeys))
) {
    echo 'only the keys ', join(', ', $wantedKeys), ' are in $_GET';
}

Comments

0

Here's an alternative solution with nested ifs (which might perform better) :

<?php

if (isset($_GET['p'])) { # If parameter p exists
    if (count($_GET) == 1) { # If only p exists
        // Do something
    } else { # If other parameters exist
        // Do something else
    }
} else { # If p doesn't exist
    // Do yet something else
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.