Will isset() return false if I assign NULL to a variable?
Asked Answered
P

3

24

I mean... I "set" it to NULL. So isset($somethingNULL) == true?

Performative answered 31/12, 2009 at 15:48 Comment(7)
why haven't you tried it yourself?Flong
Would have taken less time to test than to ask the question. You even typed the code needed to test your question into the question itself.Jaquiss
now you know you have to search php.net/manual for php reference documentation related questions :)Kayseri
I just love you all, that's why I come here for every reason I can find ;)Performative
It took me less time to find this question and answer than it would have taken to figure out test cases, write code, and run it, and still not be sure if I had covered all cases.Viniferous
@Flong because it can then help others that have the same question.Gosse
@Flong what's wrong with documenting the answer?Geronimo
K
33
bool isset ( mixed $var [, mixed $var [, $... ]] )

Determine if a variable is set and is not NULL.

If a variable has been unset with unset(), it will no longer be set. isset() will return FALSE if testing a variable that has been set to NULL. Also note that a NULL byte ("\0") is not equivalent to the PHP NULL constant.

Return values

Returns TRUE if var exists and has value other than NULL, FALSE otherwise.

From the manual. Examples on the same page.

Kayseri answered 31/12, 2009 at 15:51 Comment(4)
So how can I check for array key existence? Prior to finding this question, I thought isset returns true for null variables/keys.Nubia
@TomášZato Use array_key_exists() instead.Madlin
A similar function exists for objects: property_exists()Terreverte
thanks ! i guess we can agree that this property is poorly named, since "setting to null" is a perfectly valid expressionRawlins
S
33

Yes - from the ISSET() documentation:

$foo = NULL;
var_dump(isset($foo));   // FALSE

/* Array example */
$a = array ('test' => 1, 'hello' => NULL);

var_dump(isset($a['test']));            // TRUE
var_dump(isset($a['foo']));             // FALSE
var_dump(isset($a['hello']));           // FALSE
Selfsacrifice answered 31/12, 2009 at 15:51 Comment(1)
Rather copy pasting the doc as I did :D But we're doing it to avoid just putting a link in case it gives a 404 afterwards (unlikely to happen with php.net though)Kayseri
R
3

If you need to check if an array contains a key but its value is null, you can use array_key_exists

<?php

$array = [
    'qwe' => null,
    'foo' => 123,
];

var_dump(isset($array['foo']));            // bool(true)
var_dump(array_key_exists('foo', $array)); // bool(true)

var_dump(isset($array['qwe']));            // bool(false)
var_dump(array_key_exists('qwe', $array)); // bool(true) <---

var_dump(isset($array['bar']));            // bool(false)
var_dump(array_key_exists('bar', $array)); // bool(false)
Riarial answered 28/4, 2022 at 17:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.