if($ variable)和if(isset($ variable))之间的区别

What is the difference between something like this:

if(isset($variable)) { 

  do_something(); 

}

and this

if($variable) { 

  do_something(); 

}

I want to say that the first case, isset checks to see if the variable exists and is not null. But what if it's set to an empty array?

In the second case, I want to say that if the variable has been instantiated at all, it will pass as true.

Thank you for any future clarification.

if(isset($variable))

checks if the variable exists and is set (different from NULL).

if($variable)

just checks what boolean the variable sends back, in this case its like

if($variable === true)

The isset function checks whether a variable has been defined. It returns true on an empty array. Use empty to check if an array is empty (also returns false if variable is not defined).

Simply calling if($variable) checks whether this has a true return value (not necessarily a boolean though) and may throw you an error if it has not been defined.

Isset is a condition for weather a variable is set or not. This does not include "null", as stated from the manual:

isset — Determine if a variable is set and is not NULL http://uk1.php.net/manual/en/function.isset.php

$var = null;
if (isset($var)) {
    echo 'Hello World';
}

Would not output anything, because null is not defined as being set.

$var = false;
if (isset($var)) {
    echo 'Hello World';
}

The output would be 'Hello World', because $var is set, boolean doesn't matter.

$var = null;
if ($var) {
    echo 'Hello World';
}

Would output nothing, because $var is null, and null is not true. Same if $var = false, I think that much is a given though.

This is good for dynamically generated arrays

$array = array('hello' => 'world');
if (isset($array['hello'])) {
    echo 'hello is set';
}

if (isset($array['world'])) {
    echo 'world is set';
}

Only 'hello is set' would echo. This means you can reduce php notices significantly with 1 line:

$var = isset($_GET['var']) ? trim($_GET['var') : null;

Even if something is empty, isset would return true,

$array = array();
if (isset($array)) {
    echo 'yep, array is set!';
}

So don't use it to check for empty, do empty() instead, or in most cases you can just do if ($var) even for empty array, empty array = false.