To my understanding, in oppose to javascript which offers the convenient if (var) {}, even if var doesn't exist, in PHP you have to use if (isset(var)) {}, or if (isset(var) && var) {}.
Today I've stumbled upon a login tutorial that seems to be from a reliable source, in which isset is not used:
if(!$_SESSION['id']):
[From the linked page, demo.php section, line 15]
On my local sever, this line breaks when $_SESSION['id'] is not set, which is, IMHO, an expected behaviour. $_SESSION['id'] is not defined prior to this line.
Is there a mysterious way to avoid the annoying isset() check?
Your application doesn't "break", because it is just a notice and yes: You should always test the existence of array keys, if you are unsure, whether they exists, or not.
$defaults = array('id' => null);
$session = array_merge($defaults, $_SESSION);
Now you can be sure, that $session has a key id.
However, your can suppress warnings and notices with #
if (!#$_SESSION['id']) { /* .. */ }
But usually if you ever touch the # key:
You have a really good reason
You did something wrong :)
In a clean application you need # only in some very rare cases.
A word at the end: Never use values from outside without validation!
if(!$_SESSION['id']) will just check if the session variable is blank. isset checks if it's NULL. Personally empty() is the way to go. It checks:
"" (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)
Related
Knowing the differences of array_key_exists() and isset() in PHP, I see a lot of advocates on the web suggesting for replacing array_key_exists() with isset(), but I am thinking is it safe to do so?
In one project, I have the value of $var submitted by users. The value can be anything, even NULL or not set at all. I want to use !empty($var) to check if $var holds a non-empty value, but I understand that using !empty($var) alone is dangerous since if $var isn't pre-defined, PHP will throw an error.
So I have isset($var) && !empty($var) for checking whether $var holds a non-empty value.
However, things get complicated when I have a value stored in an assoc array. Compare the followings, assuming array $arr always exists but the key foo may or may not exist in $arr.
// code snipplet 1
$arr = array();
echo isset($arr['foo']);
// code snipplet 2
$arr = array();
echo array_key_exists('foo', $arr) && !is_null($arr['foo']);
Code snipplet 2 will always work but it seems clumsy and harder to read. As for code snipplet 1, I had bad experience... I wrote something like that before in the past on a development machine. It ran fine, but when I deployed the code to the production machine, it threw errors simply because key didn't exist in array. After some debugging, I found that the PHP configs were different between the development and the production machines and their PHP versions are slightly different.
So, I am thinking is it really that safe to just replace array_key_exists() with isset()? If not, what can be of better alternatives of code snipplet 2?
In one project, I have the value of $var submitted by users.
How does that work? Users shouldn't be able to set variables. They should be able to, e.g., submit form values which end up in $_POST. I repeat, they should not be able to directly create variables in your scope.
If "users" here means some sort of plugin system where people write and include PHP code… then you may want to think about defining a more stable interface than setting variables.
The value can be anything, even NULL…
Not if it's a value submitted through HTTP. HTTP has no concept of null. It's either an empty string or doesn't exist at all.
using !empty($var) alone is dangerous since if $var isn't pre-defined, PHP will throw an error
That is wrong. empty specifically exists to test a variable against false without throwing an error. empty($var) is the same as !$var without triggering an error if the variable doesn't exist.
So I have isset($var) && !empty($var) for checking whether $var holds a non-empty value.
See Why check both isset() and !empty(). (Spoiler: it's redundant.)
echo isset($arr['foo']);
echo array_key_exists('foo', $arr) && !is_null($arr['foo']);
These both do exactly the same thing. isset returns true if the value exists and its value is not null. The second line returns true if the array key exists and its value is not null. Same thing.
I had bad experience...
You'd need to be more detailed about that, since there should be no caveat to isset as you describe it.
See The Definitive Guide To PHP's isset And empty and Difference between isset and array_key_exists.
I am new to the concept of empty and null. Whilst I have endeavoured to understand the difference between them, I am more confused. I came across an article at http://www.tutorialarena.com/blog/php-isset-vs-empty.php however I still don't see when you would use isset and empty when validating forms. Seeing that I don't grasp the difference, I don't want to be using the incorrect functions as well as not be able to use the functions in other areas. Can someone give examples that will help me understand? I am very new to coding so would appreciate if someone could give me real world examples and at the same time keep it simply enough for noob to follow.
A variable is NULL if it has no value, and points to nowhere in memory.
empty() is more a literal meaning of empty, e.g. the string "" is empty, but is not NULL.
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 $var; (a variable declared, but without a value in a class)
Source.
Example
$a is NULL.
$a = '' is empty, but not NULL.
Update
If $a='' is empty but not NULL, when do I use the empty() function and when do I use the isset() function.
isset() will return FALSE is the variable is pointing to NULL.
Use empty() when you understand what is empty (look at the list above).
Also when you say it points nowhere in memory, what does that mean exactly?
It means that $str = '' will be in memory as a string with length of 0.
If it were $str = NULL, it would not occupy any memory.
Null is a placeholder that generally means "no data about this is available".
The use of null for this is just a convention, but a rather widespread one, to the point where some programming languages support the convention directly. The reason this convention exists has IMHO historically to do with "pointers";
many times a procedure will be defined to return a pointer to an answer, and will return what is traditionally called a Null pointer if it could not produce an answer for some reason.
Empty means (if this is a set) that it has no members. That's an explicit answer, and it is very different than "no data about this is available".
In the PHP world, apparantly uninitialized variables have the Null value, and isset on such a variable returns FALSE.
For arrays and strings, PHP follows the convention that "empty" means "has no members" although arrays and strings are not technically sets.
PHP apparantly has this funny idea that 0 and 0.0 are also "empty", by PHP design. That's abusive of the concept of "empty" IMHO: Individual numbers are not sets, so 0 can't reasonably by "empty". THis just leads to obscure programming because it violates the principle of least surprise. I'm sure the PHP designers would are that "zero is the empty number" as some kind of vague analogy; but the if analogy is vague, why bother with it? But then PHP is full of silly ideas.
The table below is an easy reference for what these functions will return for different values. The blank spaces means the function returns bool(false).
refer this link for more https://www.virendrachandak.com/techtalk/php-isset-vs-empty-vs-is_null/
NULL is a special value which explicitly states that the variable has not been set to any value yet. Be careful with using the empty() function as you can't just determine that a variable is exactly NULL using it. For example the empty() function will return true if an int is set to 0. If you need to make sure a variable is exactly NULL use if($variable == NULL).
For more info on empty() see http://php.net/manual/en/function.empty.php
There are some good answers here, which I won't repeat. In the case of validating forms, though, when a form is submitted, the value of each form input element is sent to the server in the $_POST variable. You can check for the existence of a particular input by using isset().
isset($_POST['username'])
If this returns true, then this request to the server was the result of posting a form containing an input element named "username". Now that we know that we have a value for that form element, we can see if it has a valid value. empty() will tell us whether the user actually entered any data in the field, or whether they left it empty.
empty($_POST['username'])
If that returns true then the form submitted to the server had a field named "username" but the user didn't enter anything into before submitting the form.
Been awhile since i used PHP but if other languages are anything to go by empty will indicate an existing object/map/array that has no contents while null would indicate a variable that has no meaning/definition at all (uninitialised).
In database SQL, NULL means "no value".
The empty() is a nice fast way to see if the variable holds any useful info... that is for strings empty() returns true for a string of "" as well as a null string.
So you can write something like this:
if (! empty($name)) echo $name;
More info see here: PHP: empty()
isset() returns true if both these conditions are met:
The variable has been defined and has not yet been unset.
The variable has a non-null value in it.
A variable is automatically defined when it gets set to something (including null). This has a direct implication in arrays.
$a=array();
$a['randomKey']=true;
$a['nullKey']=null;
var_dump(isset($a['randomKey'])); // true
var_dump(isset($a['nullKey'])); // true, the key has been set, set to null!
var_dump(isset($a['unsetKey'])); // false !
unset($a['randomKey']);
var_dump(isset($a['randomKey'])); // false ! it's been unset!
From above, you can check if various $_POST fields have been set. For example, a page that has been posted to, stands to reason, has the submit button name in the $_POST field.
empty() on the other hand, tests if the variable holds a non zero value. This means that values that (int) cast to 0, return false too. You can use this to see if a specific $_POST field has data in it.
This concept can be better understood from mathematics. Have you ever tried dividing a number (not zero) by 0 using a calculator e.g 7/0? You will get a result that looks like something this: undefined, not a number, null etc. This means that the operation is impossible, for some reasons (let's leave those reasons to be discussed another day).
Now, perform this: 0/7. You will get the output, 0. This means that the operation is possible and can be executed, but you the answer is just 0 because nothing is left after the division. There is a valid output and that output is zero.
In the first example, not only was the output invalid, the operation was not possible to execute. This is akin to null. The second example is akin to empty.
so if I have this code:
$bla = 1;
if($foo && $bla) do_whatever...
I get a notice telling me that $foo is a undefined variable.
So I have to change my code to this:
$bla = 1;
if(isset($foo) && $foo && $bla) do_whatever...
Is there anyway I can avoid checking if a variable is assigned and just assume the variable is false, but without having to turn off PHP notices?
Depending on the exact behavior you want, you can check if the variable is empty():
Returns FALSE if var has a non-empty
and non-zero value.
The following things are considered to
be empty:
"" (an empty string) 0 (0 as an
integer) "0" (0 as a string) NULL
FALSE array() (an empty array) var
$var; (a variable declared, but
without a value in a class)
It's important to understand all those cases, but it's handy language construct. if $foo is undefined if($foo) will throw a notice, but if(!empty($foo)) will not -- the expression will evaluate to false
This should not be abused, however. As others have stated, those notices are for your protection, so if you can define your variables, you should do so. Where empty() comes in especially handy is things like if (!empty($_GET['foo'])) - testing for the existence of input in superglobals.
The entire point of notices is to tell you that something might be wrong (such as writing $fooo instead of $foo). So, if you're not going to use them, you might as well disable them. You can disable a notice selectively by setting your own error handler, and discarding the error silently when it's of the "undefined variable" kind.
Of course, the clean thing to do would be to define your variables in the first place.
No, there isn't.
No, you should always know exactly what's going on with your variables. In fact, you should never need to use isset() on a variable itself at all.
You could do:
if(#$foo && $bla) do_whatever...
The # will suppress the warning.
But you really shouldn't do it. Not checking ALL your input is just plain WRONG.
Yesterday, I posted an answer to a question that included several (unknown to me at the time) very bad code examples. Since then, I've been looking at my fundamental knowledge of PHP that allowed me to think that such code is possible. This brings me to a question that I can't seem to find an answer to:
If I want to check for whether or not a variable has anything set, is it a valid practice to not use isset() or another helper function? here's a "for instance":
if($not_set){
//do something
} else {
//do something else
}
Rather than...
if(isset($not_set)){
//do something
} else {
//do something else
}
From the name of the variable, you can see that this variable is not set. Therefore the conditional would be false and the else portion would run. Up until now I have been using this practice, but after the posts yesterday, I now have an inkling that this is wrong.
Here's why I thought that it would be an ok practice to leave out the isset() function above. From PHP manual:
The if construct is one of the most
important features of many languages,
PHP included. It allows for
conditional execution of code
fragments. PHP features an if
structure that is similar to that of
C:
if (expr) statement
As described in the section about
expressions, expression is evaluated
to its Boolean value. If expression
evaluates to TRUE, PHP will execute
statement, and if it evaluates to
FALSE - it'll ignore it. More
information about what values evaluate
to FALSE can be found in the
'Converting to boolean' section.
And from the 'Converting to boolean section':
When converting to boolean
, the following values are considered
FALSE:
...
* the special type NULL (including unset variables)
Why would the manual go out of its way to state that unset variables are included if this is a bad practice? If it's unset, it gets converted to NULL and therefore is evaluated properly by the conditional. Using isset() will find the same result, but will take extra cycles to do so.
Have I been wrong this whole time, and if so, why? (And just how bad it is, maybe?)
If the variable is not set you get a Notice. If you use isset() you don't get a notice. So from an error reporting point of view, using isset() is better :)
Example:
error_reporting(E_ALL);
if($a) {
echo 'foo';
}
gives
Notice: Undefined variable: a in /Users/kling/test on line 5
whereas
error_reporting(E_ALL);
if(isset($a)) {
echo 'foo';
}
does not output anything.
The bottom line: If code quality is important to you, use isset().
It's okay but not good practice to use if to check for a set variable. Two reasons off the top of my head:
Using isset makes the intent clear - that you're checking whether the variable is set, and not instead checking whether a condition is true.
if ($not_set) will evaluate to false when $not_set is actually set but is equal to boolean false.
You will run in to problems if your variable is set, but evaluates to FALSE, like the following:
the boolean FALSE itself
the integer 0 (zero)
the float 0.0 (zero)
the empty string, and the
string "0"
an array with zero elements
an object with zero member
variables (PHP 4 only)
the special type NULL (including
unset variables)
SimpleXML objects created from empty
tags
Taken from the PHP manual.
Basically, using isset() is showing that you are explicitly checking if a variable exists and is not NULL, while the structure of your if statement only checks if the variable is true. It is more clear and less error-prone.
It is a common practise, but is not good -- you should always use isset!
If your $not_set is set, and is a bool with the value false, your "test" will fail!
isset works as a guard preventing you from using variables that do not actually exist.
if (isset($foo)) and if ($foo) do not mean the same thing. isset just tells you if the variable actually exists and if it's okay to use it, it does not evaluate the value of the variable itself*.
Hence, you should usually use one of these two patterns:
If the variable is sure to exist and you just want to check its value:
if ($foo == 'bar')
If the variable may or may not exist, and you want to check its value:
if (isset($foo) && $foo == 'bar')
If you're just interested that a variable is set and evaluates to true, i.e. if ($foo), you can use empty:
if (isset($foo) && $foo)
// is the same as
if (!empty($foo))
* it does check for null, where null is as good as not being set at all
What is the best way to define that a value does not exist in PHP, or is not sufficent for the applications needs.
$var = NULL, $var = array(), $var = FALSE?
And what is the best way to test?
isset($var), empty($var), if($var != NULL), if($var)?
Initializing variables as what they will be, e.g. NULL if a string, array() if they will be arrays, has some benefits in that they will function in the setting they are ment to without any unexpected results.
e.g. foreach($emptyArray) won't complain it just wont output anything, whereas foreach($false) will complain about the wrong variable type.
But it seams like an unnecessary hassle to have so many different ways of doing basically the same thing. eg. if(empty($var)) or if ($var == NULL)
Duplicate: Best way to test for a variable’s existence in PHP; isset() is clearly broken
Each function you named is for different purposes, and they should be used accordingly:
empty: tells if an existing variable is with a value that could be considered empty (0 for numbers, empty array for arrays, equal to NULL, etc.).
isset($var): tells if the script encountered a line before where the variable was the left side of an assignment (i.e. $var = 3;) or any other obscure methods such as extract, list or eval. This is the way to find if a variable has been set.
$var == NULL: This is tricky, since 0 == NULL. If you really want to tell if a variable is NULL, you should use triple =: $var === NULL.
if($var): same as $var == NULL.
As useful link is http://us2.php.net/manual/en/types.comparisons.php.
The way to tell if the variable is good for a piece of script you're coding will entirely depend on your code, so there's no single way of checking it.
One last piece of advice: if you expect a variable to be an array, don't wait for it to be set somewhere. Instead, initialize it beforehand, then let your code run and maybe it will get overwritten with a new array:
// Initialize the variable, so we always get an array in this variable without worrying about other code.
$var = array();
if(some_weird_condition){
$var = array(1, 2, 3);
}
// Will work every time.
foreach($var as $key => $value){
}
Another thing to remember is that since php is liberal in what it allows to evaluate to NULL or empty, it's necessary to use the identity operators (===, !== see http://php.net/operators.comparison. This is the reason why all of these comparison and equality functions exists, since you often have to differentiate between values with subtle differences.
If you are explicitly checking for NULL, always use $var === NULL
My vote goes for unset(), because non existing variables should generate an notice when used.
Testing gets a bit more complicated, because isset() wil be false if the variable is "not existings" or null. (Language designflaw if you'd ask me)
You could use array_key_exists() for valiables in $GLOBALS, $_POST etc.
For class properties there is property_exists().