2
if((isset($_GET[example]))&&($_GET['example']=='somevalue')){ ... }

OR

if((!empty($_GET[example]))&&($_GET['example']=='somevalue')){ ... }

OR just

if($_GET['example']=='somevalue'){ ... }

I am asking that why I have seen many example where people check first if $_GET['example'] is set and then if $_GET['example']=='somevalue' ( first and second example above ). I don't understand why not just use the last solution ( if $_GET['example']=='somevalue' then $_GET['example'] is obviously set ).

This question refers to any other variable ( $_POST, $_SERVER, ecc ).

xRobot
  • 25,579
  • 69
  • 184
  • 304
  • Eschewing notices, which are commonly misunderstood as errors. It's also frequently rationalized as micro optimization. – mario Jun 04 '12 at 16:09
  • possible duplicate of [Are there any essential reasons to use isset() over @ in php](http://stackoverflow.com/questions/7558523/are-there-any-essential-reasons-to-use-isset-over-in-php) – mario Jun 04 '12 at 16:12
  • Basics of accessing arrays... http://php.net/manual/en/language.types.array.php – Mike B Jun 05 '12 at 13:09

6 Answers6

8
if((isset($_GET[example]))&&($_GET['example']=='somevalue')){ ... }

Is the right one, you want to know that the "variable" exists (or is set) in order to use it. Empty just checks wether it has data of any kind or not. For example:

<?php
$foo= 0;

if (empty($foo)) { // True because $foo is empty
    echo '$foo is either 0, empty, or not set at all';
}

if (isset($foo)) { // True because $foo is set
    echo '$foo is set even though it is empty';
}

if (isset($var)) { // FALSE because $var was not declared before
   ...
}
?>
Nicolás Torres
  • 1,385
  • 8
  • 13
  • Ok but if $_GET['example']=='somevalue' then $_GET['example'] is obviously set, so why I need to check also if it is set ? – xRobot Jun 04 '12 at 16:14
  • 1
    Because if you try to access `$_GET['example']` and it's not set, you'll get a notice (or a warning, can't remember). So by testing with `isset` first, you avoid this notice. – nickb Jun 04 '12 at 16:17
  • No, if isset($_GET[example]) THEN it'll check ($_GET['example']=='somevalue'). If it's not set then it does nothing or goes straight to else. – Nicolás Torres Jun 04 '12 at 16:17
  • 1
    Here's a nice little spreadsheet on results from empty, isset, et al: http://itslennysfault.com/stuff/emptytest.php – Steve H Jun 04 '12 at 16:38
  • @xRobot: You're assuming that `$_GET['example']` will always be set to something; however, you can't guarantee that. For example, _example.com/myphp.php?example=_ `$_GET['example']` is set and is equal to an empty string. _example.com/myphp.php?bob=_ `$_GET['example']` is not set and is not the same as an empty string. – Herbert Jun 04 '12 at 17:22
  • 1
    Exactly, as @Herbert says, you cannot guarantee that it will be set, at least not with $_GET and $_POST requests. You have to think in the worst scenario, always. Always code thinking that somebody outthere has bad intentions. – Nicolás Torres Jun 04 '12 at 17:45
4

The differences between isset and empty are subtle but important. They are most relevant when used alone. If you are checking that a variable exists and is a truethy value (e.g. any string that is not all spaces or 0s) you can use either interchangeably.

When to use isset

Use isset when it's important to know if the variable has been defined and is not null:

if (isset($maybeExistsMaybeNull)) {
    // variable defined and is not NULL
}

When to use !empty

Use !empty when it's important to know if the variable has be defined and is truthy

if (!empty($mightBeEmpty)) {
    // variable defined, and isn't "", " ", 0, "0" etc.
}

!empty is a great shorthand for exists and is something.

When to use array_key_exists

Use array_key_exists when it's important to know if the key exists and the value is of no importance:

if (array_key_exists('something', $array)) {
    // $array['something'] exists, could be literally anything including null
}

When not to use isset

If your code looks like this:

if (isset($something) && $something) {
    // code is shorter with !empty
}

When not to use !empty

If your code looks like this:

if (!empty($something) && $something === "") {
    // you meant isset. this is unreachable.
}

Then you're writing code that can't be executed

Code that throws errors is error prone

Avoid writing code that issues notices/warnings that you are ignoring. For example in the question:

if((isset($_GET[example]))&&($_GET['example']=='somevalue')){ ... }

The first use of example is an undeclared constant. Or is it undeclared - what if you've got define('example', "foo"); somewhere else in the code.

if($_GET['example']=='somevalue'){ ... }

If the url doesn't contain ?example=.. that's going to issue a notice too.

Writing code without displaying errors means you can very easily miss mistakes like the first.

In context: isset and !empty are equivalent

For the example given, these two language constructs act exactly the same.

There is no case where one will act differently than the other, neither will issue a notice if the variable is undefined, and no measurable difference in performance between the two.

AD7six
  • 63,116
  • 12
  • 91
  • 123
  • Still not a massive fan of using !empty() but I agree with what your saying. The only thing I would say is depending on the expected data I personally wouldn't use '===' for $_POST / $_GET data in the first instance as you would need to make sure that the data types match as of course using '===' 0 would not equal '0' which could cause problems in certain circumstances. – Steve H Jun 04 '12 at 17:40
  • Not to be on your case, but on second thought I don't think using !empty() should be encouraged on $_POST / $_GET data as in your second example (using empty()) it does not make sense in certain circumstances. For example if the 'somevalue' was an int 0 or string '0' (which is quite possible with form data) the second method would fail by using !empty()) even though you want the value to be a 0. Whereas the first solution would pass. Likewise there may be a case where you do actually want an empty array(), again using !empty() would fail this. – Steve H Jun 04 '12 at 17:59
  • 3
    +1 to your edit, thanks, good additional notes you made and also good note on array_key_exists(). – Steve H Jun 04 '12 at 18:53
3

As others have said for checking things like $_GET and $_POST you would ideally want to use:

if ( isset($_GET['example']) && $_GET['example'] =='somevalue' ) {

// process data

}

So you always want to firstly make sure that the variable has been set (and not set to null) or in other words exists. Then proceed to check if the variable contains the data that you were expecting. If you try to make reference to a variable which doesn't exist (by not checking isset()) php will give you a notice saying 'undefined variable...etc etc'.

If you wanted to find out if a variable is set but are not concerned too much by what then you could use:

if ( !empty($_GET['example']) ) {

// process data

}

But I would be careful about using empty() on strings in this regard as empty can behave strangely with string data like '0' or ' '.

So I would always do the first one, to a) make sure the variable exists and b) is what you were expecting it to be.

Steve H
  • 561
  • 3
  • 5
  • `if ( isset($_GET['example']) && !empty($_GET['example']) ) {` is a needless repetition. It's the same as `if (!empty($_GET['example']) {` since it's impossible for a variable to be truthy and not set. In the context of the question `isset` and `!empty` can be used interchangably. – AD7six Jun 04 '12 at 16:39
  • 1
    True,I have amended my answer as such. I guess the only thing I was was trying to highlight was being explicit in checking values. For readability if nothing else the isset() combined with checking the actual value is in my opinion much nicer than using !empty(), good spot though. – Steve H Jun 04 '12 at 17:33
0

This is something that you'll probably do a lot of and it helps to put together a class/functions which handles this checking for you so you dont have to do it everytime.

function checkValue($key, $value) {
    if(array_key_exists($key, $_REQUEST)){
        if ($_REQUEST[$key] == $value) {
            return true;
        } else {
            return false;
        }

    } else {
        return false;
    }
}

I just use Request as a default instead of switching out (though it is preferable to switch in some cases between POST and GET for security (imo)).

Now you can just call this function anywhere if (checkValue('Item', 'Tom') === true){} etc

Alex Kremer
  • 128
  • 1
  • 7
-1

the best is

if((isset($_GET[example]))&&('somevalue'==$_GET['example'])){ ... }

The difference between

'somevalue'==$_GET['example']

AND

$_GET['example']=='somevalue'

If you mistype the == and type = instead, the first notaion will raise an error to notify you.

ilyes kooli
  • 11,959
  • 14
  • 50
  • 79
-1
if((isset($_GET[example]))&&($_GET['example']=='somevalue')){ ... }
ilyes kooli
  • 11,959
  • 14
  • 50
  • 79