Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the PHP equivalent of Javascript's undefined?

Tags:

php

null

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?

like image 577
Trindaz Avatar asked Jul 01 '13 06:07

Trindaz


People also ask

What is undefined in PHP?

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.

How check variable is empty in PHP?

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.

How do you check if a variable is defined in PHP?

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.


2 Answers

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;
}
like image 192
Elias Van Ootegem Avatar answered Oct 13 '22 01:10

Elias Van Ootegem


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.

like image 4
Marty Avatar answered Oct 13 '22 01:10

Marty