为什么trim()会使一个不存在的变量存在?

I have the following code:

$a=$_POST['dsaghgjjkhfdsfdsfsdfdsjhkhkhgj'];

if(isset($a))
{
    echo"exists";
}
else
{
    echo"does not exist";
}

echos the value "does not exist", HOWEVER when i apply trim to the $_POST variable,

$a=trim($_POST['dsaghgjjkhfdsfdsfsdfdsjhkhkhgj']);

if(isset($a))
{
    echo"exists";
}
else
{
    echo"does not exist";
}

the code will echo "exists". Why does passing in a non-existing $_POST variable to trim() magically makes it exist?

This is exactly what happens, step by step.

When you refer to $_POST['...'] in the second code snippet this notice is issued:

Notice: Undefined index: ... on line ...

You don't get the notice as your error_reporting level does not include E_NOTICE. The intermediate $_POST['...'] is evaluated NULL and trim(NULL) returns an empty string. So $a is assigned an empty string.

If you prepend error_reporting(E_ALL) and ini_set("display_errors", "on") to your script, you will see the actual errors/warnings/notices issued.

Because trim returns a string, regardless of its inputs, see http://ch2.php.net/manual/en/function.trim.php.

php > var_dump(NULL);
NULL
php > var_dump(trim(NULL));
string(0) ""

A string, even if it is empty, is declared as "defined". This is why isset returns true then.

You could try empty() function. trim() is returning an empty string != NULL:

$a=trim($_POST['dsaghgjjkhfdsfdsfsdfdsjhkhkhgj']);

if(empty($a))
{
    echo"does not exist";
}
else
{
    echo"exists";
}

From php.net:

The following things are considered to be empty:

"" (an empty string)
0 (0 as an integer)
0.0 (0 as a float)
"0" (0 as a string)
NULL
FALSE
array() (an empty array)
$var; (a variable declared, but without a value)

This is what isset does:

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

In your first example, the $_POST variable doesn’t exist. Non-existing variables have the value null:

A variable is considered to be null if:

  • it has been assigned the constant NULL.
  • it has not been set to any value yet.
  • it has been unset().

So $a does also equal null. Although $a exists, it has the value null, so isset returns false.

In your second example, null is passed to trim, which returns an empty string:

var_dump(trim(null)); // string(0) ""

So $a does also equal an empty string. And since $a exists and has value other than null, isset returns true.