How exactly does if($variable) work?
The construct if ($variable)
tests to see if $variable
evaluates to any "truthy" value. It can be a boolean TRUE
, or a non-empty, non-NULL value, or non-zero number. Have a look at the list of boolean evaluations in the PHP docs.
From the PHP documentation:
var_dump((bool) ""); // bool(false)
var_dump((bool) 1); // bool(true)
var_dump((bool) -2); // bool(true)
var_dump((bool) "foo"); // bool(true)
var_dump((bool) 2.3e5); // bool(true)
var_dump((bool) array(12)); // bool(true)
var_dump((bool) array()); // bool(false)
var_dump((bool) "false"); // bool(true)
Note however that if ($variable)
is not appropriate to use when testing if a variable or array key has been initialized. If it the variable or array key does not yet exist, this would result in an E_NOTICE Undefined variable $variable
.
What does if (!$variablename) do in PHP?
Whatever is in the variable is converted to a Boolean (the variable itself of course remains intact), and then a NOT operation (!
) is done on the resulting Boolean. The conversion will happen because !
is a Logical Operator and only works on Boolean values.
When converting to boolean, the following values are considered FALSE:
- 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
Tip: If the variable is not expected to be Boolean, you might want to use something more specific like isset($variable)
, empty($variable)
, $variable === ''
, etc. depending on what you want to check for. Check the manual for details.
JavaScript check if variable exists (is defined/initialized)
The typeof
operator will check if the variable is really undefined.
if (typeof variable === 'undefined') {
// variable is undefined
}
The typeof
operator, unlike the other operators, doesn't throw a ReferenceError exception when used with an undeclared variable.
However, do note that typeof null
will return "object"
. We have to be careful to avoid the mistake of initializing a variable to null
. To be safe, this is what we could use instead:
if (typeof variable === 'undefined' || variable === null) {
// variable is undefined or null
}
For more info on using strict comparison ===
instead of simple equality ==
, see:
Which equals operator (== vs ===) should be used in JavaScript comparisons?
The if statement doesn't work for false in php
PHP does some sneaky things in the if expression. The following values are considered FALSE:
- 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
Every other value is considered TRUE (including any resource).
You're actually passing a string that says the word false, rather than the value false itself. Because that isn't in the above list, it is actually considered true!
PHP IF statement for Boolean values: $var === true vs $var
Using if ($var === true)
or if ($var)
is not a question of style but a question of correctness. Because if ($var)
is the same as if ($var == true)
. And ==
comparison doesn’t check the type. So 1 == true
is true but 1 === true
is false.
How can I determine if a variable is 'undefined' or 'null'?
You can use the qualities of the abstract equality operator to do this:
if (variable == null){
// your code here.
}
Because null == undefined
is true, the above code will catch both null
and undefined
.
Checking if a variable exists in javascript
A variable is declared if accessing the variable name will not produce a ReferenceError
. The expression typeof variableName !== 'undefined'
will be false
in only one of two cases:
- the variable is not declared (i.e., there is no
var variableName
in scope), or - the variable is declared and its value is
undefined
(i.e., the variable's value is not defined)
Otherwise, the comparison evaluates to true
.
If you really want to test if a variable is declared or not, you'll need to catch
any ReferenceError
produced by attempts to reference it:
var barIsDeclared = true;
try{ bar; }
catch(e) {
if(e.name == "ReferenceError") {
barIsDeclared = false;
}
}
If you merely want to test if a declared variable's value is neither undefined
nor null
, you can simply test for it:
if (variableName !== undefined && variableName !== null) { ... }
Or equivalently, with a non-strict equality check against null
:
if (variableName != null) { ... }
Both your second example and your right-hand expression in the &&
operation tests if the value is "falsey", i.e., if it coerces to false
in a boolean context. Such values include null
, false
, 0
, and the empty string, not all of which you may want to discard.
JavaScript OR (||) variable assignment explanation
See short-circuit evaluation for the explanation. It's a common way of implementing these operators; it is not unique to JavaScript.
Check if a variable is of function type
Sure underscore's way is more efficient, but the best way to check, when efficiency isn't an issue, is written on underscore's page linked by @Paul Rosania.
Inspired by underscore, the final isFunction function is as follows:
function isFunction(functionToCheck) {
return functionToCheck && {}.toString.call(functionToCheck) === '[object Function]';
}
Note: This solution doesn't work for async functions, generators or proxied functions. Please see other answers for more up to date solutions.
Check if variable is false and not either true or undefined
If the variable is declared then:
if (myvar === false) {
will work fine. ===
won't consider false
to be undefined.
If it is undefined
and undeclared then you should check its type before trying to use it (otherwise you will get a reference error).
if(typeof myvar === 'boolean' && myvar === false) {
That said, you should ensure that the variable is always declared if you plan to try to use it.
var myvar;
// ...
// some code that may or may not assign a value to myvar
// ...
if (myvar === false) {
Related Topics
Create a Dynamic MySQL Query Using PHP Variables
PHP Send Mail to Multiple Email Addresses
Transfer In-Memory Data to Ftp Server Without Using Intermediate File
Can't Pass MySQLi Connection in Session in PHP
Checking If Array Is Multidimensional or Not
PHP Add Elements to Multidimensional Array with Array_Push
How to Count Unique Visitors to My Site
How to Convert Soap Response to PHP Array
How to Solve JSON_Error_Utf8 Error in PHP JSON_Decode
Php: Get HTML Source Code with Curl
PHP Function Ssh2_Connect Is Not Working
Display Float Value W/O Scientific Notation