Check if value isset and null

前端 未结 8 444
迷失自我
迷失自我 2020-11-30 01:26

I need to check if value is defined as anything, including null. isset treats null values as undefined and returns false. Take the following as an

8条回答
  •  迷失自我
    2020-11-30 02:17

    I have found that compact is a function that ignores unset variables but does act on ones set to null, so when you have a large local symbol table I would imagine you can get a more efficient solution over checking array_key_exists('foo', get_defined_vars()) by using array_key_exists('foo', compact('foo')):

    $foo = null;
    echo isset($foo) ? 'true' : 'false'; // false
    echo array_key_exists('foo', compact('foo')) ? 'true' : 'false'; // true
    echo isset($bar) ? 'true' : 'false'; // false
    echo array_key_exists('bar', compact('bar')) ? 'true' : 'false'; // false
    

    Update

    As of PHP 7.3 compact() will give a notice for unset values, so unfortunately this alternative is no longer valid.

    compact() now issues an E_NOTICE level error if a given string refers to an unset variable. Formerly, such strings have been silently skipped.

提交回复
热议问题