Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - check to see if any GET data is set [duplicate]

Tags:

php

get

Possible Duplicate:
How to check if $_GET is empty?

I'm trying to check for the condition that there is any $_GET data in my urls ?var=foo&biz=bang, and the if statement I'm currently using to do this is isset($_GET) //Do something, but it's return truey even though there isn't even any ? or & anywhere in my URL. I'm assuming that the $_GET variable is always set, so how do I check for this?

Duplicate of "How to check if $_GET is empty?"

like image 606
Kevin Beal Avatar asked Dec 07 '25 09:12

Kevin Beal


2 Answers

Since $_GET is always set in php (when run in a webserver), what you really want to know is "is anything in there?"

You want to use:

if ($_GET) {
}

This works because $_GET is an array, and an empty array will be evaluated false, while a populated array is true.


UPDATE

I no longer use the above method, since it has really negative effects on testability and CLI-run commands (phpunit, artisan).

I now always check isset() on the $_GET array. I also usually assign to an array inside the if - php evaluates these expressions to the value of the assigned variable.

If your framework has a "safe array access" function, you should always use it. If you framework has a "safe GET function" that's even better. If you aren't using a framework, or your framework does not include these helper functions, you should write them for yourself.

// example with "safe array access"
if (isset($_GET) && $value = safe_array($_GET, 'key')) {
    // do something with $value
}

// example with "safe GET function"
if ($value = safe_input_get('key')) {
    // do something with $value
}
like image 158
willoller Avatar answered Dec 08 '25 23:12

willoller


if(!empty($_GET))
{
    // do something
}

That should let you know if the get array is populated

like image 25
Kai Qing Avatar answered Dec 08 '25 22:12

Kai Qing



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!