if ($user_id == NULL || $user_name == NULL || $user_logged == NULL) {
$user_id = '-1';
$user_name = NULL;
$user_logged = NULL;
}
if ($user_admin == NULL) {
$user_admin = NULL;
}
Is there any shortest way to do it ?
And if i right, it should be tested with is_null?
It's possible $user_id, $user_name and $user_logged write in one line (maybe array?) without repeating NULL ?
If you want to test whether a variable is really NULL, use the identity operator:
$user_id === NULL // FALSE == NULL is true, FALSE === NULL is false
is_null($user_id)
If you want to check whether a variable is not set:
!isset($user_id)
Or if the variable is not empty, an empty string, zero, ..:
empty($user_id)
If you want to test whether a variable is not an empty string, ! will also be sufficient:
!$user_id
You can check if it's not set (or empty) in a number of ways.
if (!$var){ }
Or:
if ($var === null){ } // This checks if the variable, by type, IS null.
Or:
if (empty($var)){ }
You can check if it's declared with:
if (!isset($var)){ }
Take note that PHP interprets 0 (integer) and "" (empty string) and false as "empty" - and dispite being different types, these specific values are by PHP considered the same. It doesn't matter if $var is never set/declared or if it's declared as $var = 0 or $var = "". So often you compare by using the === operator which compares with respect to data type. If $var is 0 (integer), $var == "" or $var == false will validate, but $var === "" or $var === false will not.
here i have explained how the empty function and isset works please use the one that is appropriate also you can use is_null function also
<?php
$val = 0;
//evaluates to true because $var is empty
if (empty($val)) {
echo '$val is either 0, empty, or not set at all';
}
//evaluates to true because $VAR IS SET
if (isset($val)) {
echo '$val is set even though it is empty';
}
?>
empty() is a little shorter, as an alternative to checking !$user_id as suggested elsewhere:
if (empty($user_id) || empty($user_name) || empty($user_logged)) {
}
To check for null values you can use is_null() as is demonstrated below.
if (is_null($value)) {
$value = "MY TEXT"; //define to suit
}
Please define what you mean by "empty".
The test I normally use is isset().
you can use isset() routine .
also additionaly you can refer an range of is_type () functions like
is_string(), is_float(),is_int() etc to further specificaly test
1.
if(!($user_id || $user_name || $user_logged)){
//do your stuff
}
2 . No. I actually did not understand why you write such a construct.
3 . Put all values into array, for example $ar["user_id"], etc.
<?php
$nothing = NULL;
$something = '';
$array = array(1,2,3);
// Create a function that checks if a variable is set or empty, and display "$variable_name is SET|EMPTY"
function check($var) {
if (isset($var)) {
echo 'Variable is SET'. PHP_EOL;
} elseif (empty($var)) {
echo 'Variable is empty' . PHP_EOL;
}
}
check($nothing);
check($something);
check($array);
Its worth noting - and I only found this out after nearly 9 years of PHP coding that the best way of checking any variable exists is using the empty() function. This is because it doesn't generate errors and even though you turn them off - PHP still generates them! empty() however won't return errors if the variable doesn't exist. So I believe the correct answer is not to check if its null but to do the following
if (!empty($var) && is_null($var))
Note the PHP manual
variable is considered empty if it does not exist or if its value equals FALSE
As opposed to being null which is handy here!
Felt compelled to answer this because of the other responses. Use empty() if you can because it covers more bases. Future you will thank me.
For example you will have to do things like isset() && strlen() where instead you could use empty(). Think of it like this empty is like !isset($var) || $var==false
The best and easiest way to check if a variable is empty in PHP is just to use the empty() function.
if empty($variable)
then
....
Related
Could you help me to improve my coding style?:) In some tasks I need to check - is variable empty or contains something. To solve this task, I usually do the following.
Check - is this variable set or not? If it's set - I check - it's empty or not?
<?php
$var = '23';
if (isset($var)&&!empty($var)){
echo 'not empty';
}else{
echo 'is not set or empty';
}
?>
And I have a question - should I use isset() before empty() - is it necessary? TIA!
It depends what you are looking for, if you are just looking to see if it is empty just use empty as it checks whether it is set as well, if you want to know whether something is set or not use isset.
Empty checks if the variable is set and if it is it checks it for null, "", 0, etc
Isset just checks if is it set, it could be anything not null
With empty, the following things are considered 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)
From http://php.net/manual/en/function.empty.php
As mentioned in the comments the lack of warning is also important with empty()
PHP Manual says
empty() is the opposite of (boolean) var, except that no warning is
generated when the variable is not set.
Regarding isset
PHP Manual says
isset() will return FALSE if testing a variable that has been set to NULL
Your code would be fine as:
<?php
$var = '23';
if (!empty($var)){
echo 'not empty';
}else{
echo 'is not set or empty';
}
?>
For example:
$var = "";
if(empty($var)) // true because "" is considered empty
{...}
if(isset($var)) //true because var is set
{...}
if(empty($otherVar)) //true because $otherVar is null
{...}
if(isset($otherVar)) //false because $otherVar is not set
{...}
In your particular case: if ($var).
You need to use isset if you don't know whether the variable exists or not. Since you declared it on the very first line though, you know it exists, hence you don't need to, nay, should not use isset.
The same goes for empty, only that empty also combines a check for the truthiness of the value. empty is equivalent to !isset($var) || !$var and !empty is equivalent to isset($var) && $var, or isset($var) && $var == true.
If you only want to test a variable that should exist for truthiness, if ($var) is perfectly adequate and to the point.
You can just use empty() - as seen in the documentation, it will return false if the variable has no value.
An example on that same page:
<?php
$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';
}
?>
You can use isset if you just want to know if it is not NULL. Otherwise it seems empty() is just fine to use alone.
Here are the outputs of isset() and empty() for the 4 possibilities: undeclared, null, false and true.
$a=null;
$b=false;
$c=true;
var_dump(array(isset($z1),isset($a),isset($b),isset($c)),true); //$z1 previously undeclared
var_dump(array(empty($z2),empty($a),empty($b),empty($c)),true); //$z2 previously undeclared
//array(4) { [0]=> bool(false) [1]=> bool(false) [2]=> bool(true) [3]=> bool(true) }
//array(4) { [0]=> bool(true) [1]=> bool(true) [2]=> bool(true) [3]=> bool(false) }
You'll notice that all the 'isset' results are opposite of the 'empty' results except for case $b=false. All the values (except null which isn't a value but a non-value) that evaluate to false will return true when tested for by isset and false when tested by 'empty'.
So use isset() when you're concerned about the existence of a variable. And use empty when you're testing for true or false. If the actual type of emptiness matters, use is_null and ===0, ===false, ===''.
Empty returns true if the var is not set. But isset returns true even if the var is not empty.
$var = 'abcdef';
if(isset($var))
{
if (strlen($var) > 0);
{
//do something, string length greater than zero
}
else
{
//do something else, string length 0 or less
}
}
This is a simple example. Hope it helps.
edit: added isset in the event a variable isn't defined like above, it would cause an error, checking to see if its first set at the least will help remove some headache down the road.
Taking into account boolean, strings and integers. What is the best all purpose way to initialize a variable that is going to cause the least amount of problems.
It depends if you know where you are going to use the variable. What its data type is going to be.
For instance, array variables: $test = [];
If you don't know exactly for what you are going to use the variable then i advise to don't initialize it at all. In my experience, i never met the scenario where I had to necessary initialize a variable if I wasnt sure whats its nature gonna be.
We do need arrays to be initialized sometimes and for that i gave the example of initializing empty array.
Although initializing a variable with NULL might not serve your purpose if you are planning to use isset() function later on for some reason, and for rest options you mentioned, empty() function will always return true for them so maybe clear your question a bit to exactly what scenario you are talking for.
TRUE/FALSE, only use if you want to declare a Boolean variable, like if you want to check if a variable has something then declare another variable with bool
$var = "hello";
if ($var == "hello") {
$new_var = TRUE;
} else {
$new_var = FALSE;
}
NULL variable is use when you want to check if some variable is NULL or not
$var = NULL;
if ($var != NULL
{ echo "something"; }
sometimes a variable can have value 0 so we cannot check for the empty variable if we assigned it a 0 value
$var = 0;
if ($var != 0)
{ echo "something"; }
'' is mostly used to initialize a variable so that if i want to check whether a variable is empty or not and works for string or integer etc
$var = '';
if ($var != '')
{ echo "something"; }
I have a question : what is the difference between : $value !='' and !isset($value) ?
The main difference in practical use between $value != '' and !isset($value) is that you can use isset() like this:
if(!isset($value)){
echo '$value is not declared or is equal to null';
}
If $value is not actually set then you won't get a notice with isset(). If you did something like this:
if($value != ''){
echo $value." is not equal to nothing";
}
If $value is not set then this will cause a notice in PHP explaining that $value has not yet been declared.
The thing to note is that isset() will check that the variable has been declared but will not check that it isn't equal to ''.
But what about empty()?
The other part of the puzzle here would be empty() which will check whether a variable is declared and is not equal to ''. You could do something like this:
if(!empty($value)){
echo 'We know that $value is declared and not equal to nothing.';
}
which would be the same as doing this:
if(isset($value) && $value != ''){
echo 'We know that $value is declared and not equal to nothing.';
}
Further reading:
isset() - PHP docs
empty() - PHP docs
isset, empty checks - similar question
Why check both isset and empty?
All of these examples work in PHP 5.3+
$variable != '' simply checks variable against empty string value ( or null because '' == null), if variable is not defined notice will be shown.
!isset($variable) checks whether variable is defined and if it is not returns true, no error/notice will be shown.
But be aware that isset may return false even when variable is defined
$variable = null;
var_dump(isset($variable)); // prints false
To check if variable is truly defined within the current scope, use 'array_key_exists' with 'get_defined_vars'
$variable = null;
var_dump(array_key_exists('value', get_defined_vars())); // prints true
isset() will tell you about the existence of the variable and is not NULL.
empty() can tell you about both, existence of the variable & the value of the variable.
Ex.
$var1 = "";
echo isset($var1);
Output:- true
So to check if the variable was set then use isset() and if you want to check if the value of variable was not a null/empty use empty().
$value != '' means you are checking if $value is not an empty string.
!isset($value) determine if a variable $value is not set and is NULL
Read these links for more information on isset & empty
What's the difference between 'isset()' and '!empty()' in PHP?
http://php.net/manual/en/function.isset.php
http://php.net/manual/en/types.comparisons.php
I read somewhere that the isset() function treats an empty string as TRUE, therefore isset() is not an effective way to validate text inputs and text boxes from a HTML form.
So you can use empty() to check that a user typed something.
Is it true that the isset() function treats an empty string as TRUE?
Then in which situations should I use isset()? Should I always use !empty() to check if there is something?
For example instead of
if(isset($_GET['gender']))...
Using this
if(!empty($_GET['gender']))...
isset vs. !empty
FTA:
"isset() checks if a variable has a
value including (False, 0 or empty
string), but not NULL. Returns TRUE
if var exists; FALSE otherwise.
On the other hand the empty() function
checks if the variable has an empty
value empty string, 0, NULL or
False. Returns FALSE if var has a
non-empty and non-zero value."
In the most general way :
isset tests if a variable (or an element of an array, or a property of an object) exists (and is not null)
empty tests if a variable (...) contains some non-empty data.
To answer question 1 :
$str = '';
var_dump(isset($str));
gives
boolean true
Because the variable $str exists.
And question 2 :
You should use isset to determine whether a variable exists ; for instance, if you are getting some data as an array, you might need to check if a key isset in that array.
Think about $_GET / $_POST, for instance.
Now, to work on its value, when you know there is such a value : that is the job of empty.
Neither is a good way to check for valid input.
isset() is not sufficient because – as has been noted already – it considers an empty string to be a valid value.
! empty() is not sufficient either because it rejects '0', which could be a valid value.
Using isset() combined with an equality check against an empty string is the bare minimum that you need to verify that an incoming parameter has a value without creating false negatives:
if( isset($_GET['gender']) and ($_GET['gender'] != '') )
{
...
}
But by "bare minimum", I mean exactly that. All the above code does is determine whether there is some value for $_GET['gender']. It does not determine whether the value for $_GET['gender'] is valid (e.g., one of ("Male", "Female","FileNotFound")).
For that, see Josh Davis's answer.
isset is intended to be used only for variables and not just values, so isset("foobar") will raise an error. As of PHP 5.5, empty supports both variables and expressions.
So your first question should rather be if isset returns true for a variable that holds an empty string. And the answer is:
$var = "";
var_dump(isset($var));
The type comparison tables in PHP’s manual is quite handy for such questions.
isset basically checks if a variable has any value other than null since non-existing variables have always the value null. empty is kind of the counter part to isset but does also treat the integer value 0 and the string value "0" as empty. (Again, take a look at the type comparison tables.)
If you have a $_POST['param'] and assume it's string type then
isset($_POST['param']) && $_POST['param'] != '' && $_POST['param'] != '0'
is identical to
!empty($_POST['param'])
isset() is not an effective way to validate text inputs and text boxes from a HTML form
You can rewrite that as "isset() is not a way to validate input." To validate input, use PHP's filter extension. filter_has_var() will tell you whether the variable exists while filter_input() will actually filter and/or sanitize the input.
Note that you don't have to use filter_has_var() prior to filter_input() and if you ask for a variable that is not set, filter_input() will simply return null.
When and how to use:
isset()
True for 0, 1, empty string, a string containing a value, true, false
False for null
e.g
$status = 0
if (isset($status)) // True
$status = null
if (isset($status)) // False
Empty
False for 1, a string containing a value, true
True for null, empty string, 0, false
e.g
$status = 0
if(empty($status)) // true
$status = 1
if(empty($status)) // False
isset() vs empty() vs is_null()
isset is used to determine if an instance of something exists that is, if a variable has been instantiated... it is not concerned with the value of the parameter...
Pascal MARTIN... +1
...
empty() does not generate a warning if the variable does not exist... therefore, isset() is preferred when testing for the existence of a variable when you intend to modify it...
isset() is used to check if the variable is set with the value or not and Empty() is used to check if a given variable is empty or not.
isset() returns true when the variable is not null whereas Empty() returns true if the variable is an empty string.
isset($variable) === (#$variable !== null)
empty($variable) === (#$variable == false)
I came here looking for a quick way to check if a variable has any content in it. None of the answers here provided a full solution, so here it is:
It's enough to check if the input is '' or null, because:
Request URL .../test.php?var= results in $_GET['var'] = ''
Request URL .../test.php results in $_GET['var'] = null
isset() returns false only when the variable exists and is not set to null, so if you use it you'll get true for empty strings ('').
empty() considers both null and '' empty, but it also considers '0' empty, which is a problem in some use cases.
If you want to treat '0' as empty, then use empty(). Otherwise use the following check:
$var .'' !== '' evaluates to false only for the following inputs:
''
null
false
I use the following check to also filter out strings with only spaces and line breaks:
function hasContent($var){
return trim($var .'') !== '';
}
Using empty is enough:
if(!empty($variable)){
// Do stuff
}
Additionally, if you want an integer value it might also be worth checking that intval($variable) !== FALSE.
I use the following to avoid notices, this checks if the var it's declarated on GET or POST and with the # prefix you can safely check if is not empty and avoid the notice if the var is not set:
if( isset($_GET['var']) && #$_GET['var']!='' ){
//Is not empty, do something
}
$var = '';
// 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';
}
Source: Php.net
isset() tests if a variable is set and not null:
http://us.php.net/manual/en/function.isset.php
empty() can return true when the variable is set to certain values:
http://us.php.net/manual/en/function.empty.php
<?php
$the_var = 0;
if (isset($the_var)) {
echo "set";
} else {
echo "not set";
}
echo "\n";
if (empty($the_var)) {
echo "empty";
} else {
echo "not empty";
}
?>
!empty will do the trick. if you need only to check data exists or not then use isset other empty can handle other validations
<?php
$array = [ "name_new" => "print me"];
if (!empty($array['name'])){
echo $array['name'];
}
//output : {nothing}
////////////////////////////////////////////////////////////////////
$array2 = [ "name" => NULL];
if (!empty($array2['name'])){
echo $array2['name'];
}
//output : {nothing}
////////////////////////////////////////////////////////////////////
$array3 = [ "name" => ""];
if (!empty($array3['name'])){
echo $array3['name'];
}
//output : {nothing}
////////////////////////////////////////////////////////////////////
$array4 = [1,2];
if (!empty($array4['name'])){
echo $array4['name'];
}
//output : {nothing}
////////////////////////////////////////////////////////////////////
$array5 = [];
if (!empty($array5['name'])){
echo $array5['name'];
}
//output : {nothing}
?>
Please consider behavior may change on different PHP versions
From documentation
isset() Returns TRUE if var exists and has any value other than NULL. FALSE otherwise
https://www.php.net/manual/en/function.isset.php
empty() does not exist or if its value equals FALSE
https://www.php.net/manual/en/function.empty.php
(empty($x) == (!isset($x) || !$x)) // returns true;
(!empty($x) == (isset($x) && $x)) // returns true;
When in doubt, use this one to check your Value and to clear your head on the difference between isset and empty.
if(empty($yourVal)) {
echo "YES empty - $yourVal"; // no result
}
if(!empty($yourVal)) {
echo "<P>NOT !empty- $yourVal"; // result
}
if(isset($yourVal)) {
echo "<P>YES isset - $yourVal"; // found yourVal, but result can still be none - yourVal is set without value
}
if(!isset($yourVal)) {
echo "<P>NO !isset - $yourVal"; // $yourVal is not set, therefore no result
}
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Fixing the PHP empty function
In PHP, empty() is a great shortcut because it allows you to check whether a variable is defined AND not empty at the same time.
What would you use when you don't want "0" (as a string) to be considered empty, but you still want false, null, 0 and "" treated as empty?
That is, I'm just wondering if you have your own shortcut for this:
if (isset($myvariable) && $myvariable != "") ;// do something
if (isset($othervar ) && $othervar != "") ;// do something
if (isset($anothervar) && $anothervar != "") ;// do something
// and so on, and so on
I don't think I can define a helper function for this, since the variable could be undefined (and therefore couldn't be passed as parameter).
This should do what you want:
function notempty($var) {
return ($var==="0"||$var);
}
Edit: I guess tables only work in the preview, not in actual answer submissions. So please refer to the PHP type comparison tables for more info.
notempty("") : false
notempty(null) : false
notempty(undefined): false
notempty(array()) : false
notempty(false) : false
notempty(true) : true
notempty(1) : true
notempty(0) : false
notempty(-1) : true
notempty("1") : true
notempty("0") : true
notempty("php") : true
Basically, notempty() is the same as !empty() for all values except for "0", for which it returns true.
Edit: If you are using error_reporting(E_ALL), you will not be able to pass an undefined variable to custom functions by value. And as mercator points out, you should always use E_ALL to conform to best practices. This link (comment #11) he provides discusses why you shouldn't use any form of error suppression for performance and maintainability/debugging reasons.
See orlandu63's answer for how to have arguments passed to a custom function by reference.
function isempty(&$var) {
return empty($var) || $var === '0';
}
The key is the & operator, which passes the variable by reference, creating it if it doesn't exist.
if(isset($var) && ($var === '0' || !empty($var)))
{
}
if ((isset($var) && $var === "0") || !empty($var))
{
}
This way you will enter the if-construct if the variable is set AND is "0", OR the variable is set AND not = null ("0",null,false)
The answer to this is that it isn't possible to shorten what I already have.
Suppressing notices or warnings is not something I want to have to do, so I will always need to check if empty() or isset() before checking the value, and you can't check if something is empty() or isset() within a function.
function Void($var)
{
if (empty($var) === true)
{
if (($var === 0) || ($var === '0'))
{
return false;
}
return true;
}
return false;
}
If ($var != null)