0

Possible Duplicate:
is_null($x) vs $x === null in PHP

In the following context !== null, !is_null() and isset() all produce the same result:

$foo = null;

function foo() {
    if ($this->foo !== null) {
        ...
    }
    if (!is_null($this->foo)) {
        ...
    }
    if (isset($this->foo)) {
        ...
    }
}

Which one is the quickest and which would you recommend in that context?

Community
  • 1
  • 1
Adam
  • 1,164
  • 12
  • 22
  • in PHP5 you can't use isset() for variable only for http request, post or get – Rob Nov 15 '12 at 09:29
  • 3
    @Robuust What? of course you can use it for any variable. `$a = 5; if (isset($a)) { echo "a = {$a}"; }` – Corbin Nov 15 '12 at 09:30
  • 1
    Regarding which is the quickest, [a comment on php.net](http://www.php.net/manual/en/function.is-null.php#83588) included benchmarks for each of the methods looping over 10M iterations. – Beardy Nov 15 '12 at 09:30

4 Answers4

2

If you're not sure that the variable exists, use isset.

Example:

$content = (isset($_POST['content'])) ? $_POST['content'] : null;

Otherwise, use strict comparison to null.

if ($content === null) { }

(Really, I'm just pushing my opinion on your with the strict comparison. I just think it looks better than is_null, and it's probably an extremely small bit faster.)

Corbin
  • 31,183
  • 6
  • 65
  • 77
1

Use isset only if the variable may not be set. I.e. if you do not know whether the variable exists at this point or not. Since you do know that it should exist at this point, don't use isset.

The difference between !== null and !is_null is negligible and mostly depends on your preference. Personally, I like !== null.

deceze
  • 471,072
  • 76
  • 664
  • 811
0
if ($this->foo !== null) {
      //...
}

I prefer this condition.

Adi
  • 4,989
  • 6
  • 30
  • 47
rOcKiNg RhO
  • 611
  • 1
  • 6
  • 16
0

According to me

  if($this->foo!=""){

//... }

this is the quickest one and produce the result quickly

Rithu Psks
  • 92
  • 11