views:

70

answers:

1

The following code executes whether there are GET variables passed or not:

if($_SERVER['REQUEST_METHOD'] == 'GET')
{
    //Do something
}

The following only executes when GET variables are passed:

if($_GET)
{
    //Do something
}

I was under the impression that the first method was better, but now I am confused.

Any ideas? Thanks!

+4  A: 

The first code will execute when the request method is GET, even if no query string is present.
It won't be executed with a POST request type, even if there is a query string.

You have to understand that the 'GET' request type does not mean that variables were passed in the URL.

So the two codes are made for completely different tasks.

If you simply need to check if variables were passed in the URL, use the second one.

Macmade
OH! Thanks for your explanation. I did not realize that the $_GET superglobal always exists.
letseatfood
It always exists, and is always an array. But your condition is ok (I corrected my answer). If nothing is passed, it's an empty array, and your code won't be executed. : )
Macmade
Oh! Great, thanks!
letseatfood