Checking if empty vs not checking at all

Marco :

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 {
   ...
}
deceze :

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 {
   ...
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=345928&siteId=1