Check If Var Exist Before Unsetting In PHP?


Answer :

Just unset it, if it doesn't exist, nothing will be done.


From the PHP Manual:

In regard to some confusion earlier in these notes about what causes unset() to trigger notices when unsetting variables that don't exist....

Unsetting variables that don't exist, as in

<?php unset($undefinedVariable); ?> 

does not trigger an "Undefined variable" notice. But

<?php unset($undefinedArray[$undefinedKey]); ?> 

triggers two notices, because this code is for unsetting an element of an array; neither undefinedArraynorundefinedArray nor undefinedKey are themselves being unset, they're merely being used to locate what should be unset. After all, if they did exist, you'd still expect them to both be around afterwards. You would NOT want your entire array to disappear just because you unset() one of its elements!


Using unset on an undefined variable will not cause any errors (unless the variable is the index of an array (or object) that doesn't exist).

Therefore the only thing you need to consider, is what is most efficient. It is more efficient to not test with 'isset', as my test will show.

Test:

function A() {     for ($i = 0; $i < 10000000; $i++)     {         $defined = 1;         unset($defined);     } }  function B() {     for ($i = 0; $i < 10000000; $i++)     {         $defined = 1;         unset($undefined);     } }  function C() {     for ($i = 0; $i < 10000000; $i++)     {         $defined = 1;         if (isset($defined))             unset($defined);     } }  function D() {     for ($i = 0; $i < 10000000; $i++)     {         $defined = 1;         if (isset($undefined))             unset($undefined);     } }  $time_pre = microtime(true); A(); $time_post = microtime(true); $exec_time = $time_post - $time_pre; echo "Function A time = $exec_time ";  $time_pre = microtime(true); B(); $time_post = microtime(true); $exec_time = $time_post - $time_pre; echo "Function B time = $exec_time ";  $time_pre = microtime(true); C(); $time_post = microtime(true); $exec_time = $time_post - $time_pre; echo "Function C time = $exec_time ";  $time_pre = microtime(true); D(); $time_post = microtime(true); $exec_time = $time_post - $time_pre; echo "Function D time = $exec_time"; exit(); 

Results:

  1. Function A time = 1.0307259559631
    • Defined without isset
  2. Function B time = 0.72514510154724
    • Undefined without isset
  3. Function C time = 1.3804969787598
    • Defined using isset
  4. Function D time = 0.86475610733032
    • Undefined using isset

Conclusion:

It is always less efficient to use isset, not to mention the small amount of extra time it takes to write. It's quicker to attempt to unset an undefined variable than to check if it can be unset.


Comments

Popular posts from this blog

Are Regular VACUUM ANALYZE Still Recommended Under 9.1?

Can Feynman Diagrams Be Used To Represent Any Perturbation Theory?