What is the PHP equivalent of Javascript's undefined?
Not really, undefined
has no counterpart in PHP. Comparing JS's undefined
to PHP
s null
doesn't really stack up, but it's as close as you're going to get. In both languages you can assign these values/non-values:
var nothingness = undefined;
$nothing = null;
and, if you declare a variable, but don't assign it anything, it would appear that JS resolves the var to undefined
, and PHP resolves (or assigns) that variable null
:
var nothingness;
console.log(nothingness === undefined);//true
$foo;
echo is_null($foo) ? 'is null' : '?';//is null
Be careful with isset
, though:
$foo = null;
//clearly, foo is set:
if (isset($foo))
{//will never echo
echo 'foo is set';
}
The only real way to know if the variable exists, AFAIK, is by using get_defined_vars
:
$foo;
$bar = null;
$defined = get_defined_vars();
if (array_key_exists($defined, 'foo'))
{
echo '$foo was defined, and assigned: '.$foo;
}
I don't think there is undefined
. Rather than checking if something is undefined
as you would in JavaScript:
if(object.property === undefined) // Doesn't exist.
You just use isset()
:
if(!isset($something)) // Doesn't exist.
Also, I think your understanding of undefined
is a little odd. You shouldn't be setting properties to undefined
, that's illogical. You just want to check if something is undefined, which means you haven't defined it anywhere within scope. isset()
follows this concept.
That said, you can use unset()
which I guess would be considered the same as setting something to undefined
.