Marco
Marco

Reputation: 2737

Checking if empty vs not checking at all

My code is finished and i'm trying to optimize it. I was wondering if the following 2 are the same or am I missing something that could potentially cause problems later on?

$this_awardid = !empty($_POST['awardid']) ? $_POST['awardid'] : null;

if (empty($this_awardid) ) {
    ...
} elseif (!empty($this_awardid)) {
    ...
}

I've optimized the code like so... I'm assuming that $this_awardid it's NOT empty, so there is no need to verify.. Is this logic correct?

if (empty($this_awardid) ) {
   ...
} else {
   ...
}

Upvotes: 1

Views: 53

Answers (3)

deceze
deceze

Reputation: 522125

You are defining $this_awardid right there. It's guaranteed to exist. There's no need to use empty for it at all, since all empty does is suppress error messages for non-existing variables. You want error messages should you find $this_awardid to be non-existent, since that means something's very wrong with your code.

Secondly, if (a) else if (!a) is always redundant; you do not need to test for the inverse of the condition again, that is already contained in the if..else itself.

So, all you need is:

if (!$this_awardid) {
   ...
} else {
   ...
}

Upvotes: 1

Ja͢ck
Ja͢ck

Reputation: 173572

$this_awardid = !empty($_POST['awardid']) ? $_POST['awardid'] : null;

At this point in your code, $this_awardid is only assigned a value if the $_POST value present (i.e. not empty), otherwise it's set to null; therefore:

if ($this_awardid) {
    // the value has something
} else {
    // the value is null
}

This works, because !empty() is essentially isset($var) && $var == true

Upvotes: 1

Penny Codes
Penny Codes

Reputation: 182

empty returns true or false. So no need for elseif

if (empty($this_awardid) ) {

   // response here

} else {

  // proceed here
}

Hope this helps.

Upvotes: 1

Related Questions