0

While debugging some code I noticed that a call to echo isset($bar) call wasn't returning anything. Nothing at all. According to the documentation it should return false when the variable isn't declared, as it isn't in my case. I had a play in a sandbox to check my sanity. Sure enough, returns nothing. See link below.

http://sandbox.onlinephpfunctions.com/code/8c6e97b4eca5177480ec069d866c0ed38c2ae47f

I can only get a false result if I use var_dump(isset($bar));, but that yields bool(false) instead of zero. Whilst I COULD work with this can someone please explain what is going on?

<?php
$foo = 1;

$defined_vars = get_defined_vars();

echo "foo isset: ".isset($foo)."\n";       //Should print 1
echo "foo isset: ".isset($bar)."\n";       //Should print 0

echo "\nvar_dump of foo and bar:\n";
var_dump(isset($foo));                     //Should print bool(true)
var_dump(isset($bar));                     //Should print bool(false)

echo "\n";
echo  "foo array_key_exists: ".array_key_exists('foo', $defined_vars)."\n";     //Should print 1
echo  "foo array_key_exists: ".array_key_exists('bar', $defined_vars);          //Should print 0

output:

foo isset: 1

Foo isset:

var_dump of foo and bar:

bool(true)

bool(false)

foo array_key_exists: 1

foo array_key_exists:

Dharman
  • 30,962
  • 25
  • 85
  • 135
Ben
  • 427
  • 5
  • 17

1 Answers1

0

The answer is to use the empty() function to check for falsity. So rather than echo "foo isset: ".isset($bar)."\n";, use echo "foo isset: ".empty(isset($bar))."\n"; which will return true as it is empty.

I found the solution here: PHP - check if variable is undefined

Ben
  • 427
  • 5
  • 17
  • I still have the question about why false doesn't display anything. If I run empty(isset($bar)) when $bar IS defined, again php returns a blank rather than a zero. Why? – Ben Aug 20 '20 at 16:43