What does the exclamation point mean in PHP? [duplicate]

走远了吗. 提交于 2019-12-04 13:54:19

问题


Possible Duplicate:
Reference - What does this symbol mean in PHP?
Getting confused with empty, isset, !empty, !isset

In PHP what is the difference between:

if(!isset) 
if(isset)

Same with if(!empty) and if(empty)?

What does the "!" character mean?


回答1:


! is the logical negation or NOT operator. It reverses the sense of the logical test.

That is:

  • if(isset) makes something happen if isset is logical True.
  • if(!isset) makes something happen if isset is logical False.

More about operators (logical and other types) in the PHP documentation. Look up ! there to cement your understanding of what it does. While you're there, also look up the other logical operators:

  • && logical AND
  • || logical OR
  • xor logical EXCLUSIVE-OR

Which are also commonly used in logic statements.




回答2:


The ! character is the logical "not" operator. It inverts the boolean meaning of the expression.

If you have an expression that evaluates to TRUE, prefixing it with ! causes it evaluate to FALSE and vice-versa.

$test = 'value';

var_dump(isset($test));  // TRUE
var_dump(!isset($test)); // FALSE

isset() returns TRUE if the given variable is defined in the current scope with a non-null value.

empty() returns TRUE if the given variable is not defined in the current scope, or if it is defined with a value that is considered "empty". These values are:

NULL    // NULL value
0       // Integer/float zero
''      // Empty string
'0'     // String '0'
FALSE   // Boolean FALSE
array() // empty array

Depending PHP version, an object with no properties may also be considered empty.

The upshot of this is that isset() and empty() almost compliment each other (they return the opposite results) but not quite, as empty() performs an additional check on the value of the variable, isset() simply checks whether it is defined.

Consider the following example:

var_dump(isset($test)); // FALSE
var_dump(empty($test)); // TRUE

$test = '';

var_dump(isset($test)); // TRUE
var_dump(empty($test)); // TRUE

$test = 'value';

var_dump(isset($test)); // TRUE
var_dump(empty($test)); // FALSE



回答3:


$var = 0;

// Evaluates to true because $var is empty
if (empty($var)) {
    echo '$var is either 0, empty, or not set at all';
}

// Evaluates as true because $var is set
if (isset($var)) {
    echo '$var is set even though it is empty';
}

Edit:

here is a test case for you:

$p = false;
echo isset($p) ? '$p is setted : ' : '$p is not setted : ';
echo empty($p) ? '$p is empty' : '$p is not empty';
echo "<BR>";

$p is setted : $p is empty



来源:https://stackoverflow.com/questions/9994581/what-does-the-exclamation-point-mean-in-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!