rockyraw
rockyraw

Reputation: 1145

How to check for existence of parameter in url?

I want to output a message, whenever the url includes any parameter that start with p2, for example in all the following instances:

example.com/?p2=hello

example.com/?p2foo=hello

example.com/?p2

example.com/?p2=

I've tried:

if (!empty($GET['p2'])) {
    echo "a parameter that starts with p2 , is showing in your url address";

} else {
    echo "not showing";
}

Upvotes: 1

Views: 64

Answers (4)

Victor Radu
Victor Radu

Reputation: 2302

fastest way is

if(preg_match("/(^|\|)p2/",implode("|",array_keys($_GET)))){
    //do stuff
}

Upvotes: 0

Imtiaz Pabel
Imtiaz Pabel

Reputation: 5443

try

if (isset($GET['p2'])) {
echo "a paramater that starts with p2 , is showing in your url address";

} else {
echo "not showing";
}

Upvotes: 0

Alex Andrei
Alex Andrei

Reputation: 7283

Just iterate over the $_GET array and add a condition for the key to start with p2 when matching do what you need to do.

foreach($_GET as $key=>$value){
    if (substr($key, 0, 2) === "p2"){
        // do your thing
        print $value;
    }
}

substr($key,0,2) takes the first two characters from the string

Upvotes: 1

danjam
danjam

Reputation: 1062

this should cover all your cases

$filtered = array_filter(array_keys($_GET), function($k) {
    return strpos($k, 'p2') === 0;
});

if ( !empty($filtered) ) {
    echo 'a paramater that starts with p2 , is showing in your url address';
}
else {
    echo 'not showing';
}

Upvotes: 3

Related Questions