My assumption followed by question based on the assumption:
Javascript has null
and undefined
. You can set a variable to be null
, implying it has no value, or you can set it to undefined
, implying that it isn't known whether it has a value or not - it's just not set at all.
PHP has null
, which so far I've used in the same way I'd use null
in Javascript. Does PHP have an equivalent of undefined
?
It shows Undefined Offset Notice in PHP when we are referring to a key in an array that has not been set for the array.
PHP empty() Function The empty() function checks whether a variable is empty or not. This function returns false if the variable exists and is not empty, otherwise it returns true.
The isset() function checks whether a variable is set, which means that it has to be declared and is not NULL. This function returns true if the variable exists and is not NULL, otherwise it returns false.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With