1

I once thought that I read somewhere that if you have a PHP script like this:

public function test($something){
    if($something == "true") {
        return true;
    } else {
        return false;
    }
}

if(test("true")){
    echo "Returned true";
}

Then that should work fine as the if statement assumes you are checking if something is true when it is left blank? Is that true, and if so is it 'good programming' to leave it blank or should you finish off the statement for the sake of not cutting corners?

Seth McClaine
  • 9,142
  • 6
  • 38
  • 64
Benedict Lewis
  • 2,733
  • 7
  • 37
  • 78

1 Answers1

4
if($variable)

Is pretty much saying

if($variable != null && $variable != false && $variable != 0)

So as long as the variable is set and not equal to 0 or false it will be evaluated as true

"and if so is it 'good programming' to leave it blank or should you finish off the statement for the sake of not cutting corners?"

If you are trying evaluate exactly equal to true, it is cutting corners, but it is pretty common to use if($variable) to confirm that $variable is defined with a value

Seth McClaine
  • 9,142
  • 6
  • 38
  • 64
  • You see it a lot in php code when you are getting database results, if($results) will usually be null if you doesnt return anything (evaluating false) or it will be a populated array if it does (evaluating true) – Seth McClaine Jul 24 '13 at 03:56
  • 2
    @SethMcClaine: `if($variable)` checks `!=null` and `!=false` etc.. but it doesn't check `isset($variable)`. If the `$variable` is not set `if($variable)` will return a warning: undefined index.. – zzlalani Jul 24 '13 at 04:11
  • @zzlalani thanks, I couldn't remember if it did or not. I was thinking since php was so loosely typed that it didn't care if it was set – Seth McClaine Jul 24 '13 at 15:18
  • Actually I just ran it... it will return false without any errors. – Seth McClaine Jul 25 '13 at 18:16
  • It wont return error, but warning, your server might be configured to don't to show warnings.. – zzlalani Jul 26 '13 at 03:41