-1
$num = 1;    
$var = ''

if ($num == 1) {
  $var = 'ONE';
}

if (isset($var)) {
  echo $var;
}

// Result: ONE

In the above example, which is best practice when checking against isset()?

$var = '';

or

$var = null;
Script47
  • 14,230
  • 4
  • 45
  • 66
MultiDev
  • 10,389
  • 24
  • 81
  • 148

2 Answers2

2

It kind of depends more broadly on what you're trying to do.
I'm not convinced unsetting a variable is your best bet here.

However, PHP does have an unset function:

unset($var);

To be clear, I agree that checking for emptiness is probably a better idea

jcuenod
  • 55,835
  • 14
  • 65
  • 102
1

By setting $var = ''; near the top, isset will return true every time. What you want, is to check if the $var is empty.

Change:

if (isset($var)) {
  echo $var;
}

to

if (!empty($var)) {
  echo $var;
}

Otherwise, simply remove the original $var = ''; near the top and you can continue to use isset.

RhapX
  • 1,663
  • 2
  • 10
  • 17