Is there a better way besides isset() or empty() to test for an empty variable?
It depends upon the context.
isset() will ONLY return true when the value of the variable is not NULL (and thereby the variable is at least defined).
empty() will return true when the value of the variable is deemed to be an "empty" value, typically this means 0, "0", NULL, FALSE, array() (an empty array) and "" (an empty string), anything else is not empty.
Some examples
FALSE == isset($foo);
TRUE == empty($foo);
$foo = NULL;
FALSE == isset($foo);
TRUE == empty($foo);
$foo = 0;
TRUE == isset($foo);
TRUE == empty($foo);
$foo = 1;
TRUE == isset($foo);
FALSE == empty($foo);
Keep an eye out for some of the strange == results you get with PHP though; you may need to use === to get the result you expect, e.g.
if (0 == '') {
echo "weird, huh?\n";
}
if (0 === '') {
echo "weird, huh?\n";
} else {
echo "that makes more sense\n";
}
Because 0 is false, and an empty string is false, 0 == '' is the same as FALSE == FALSE, which is true. Using === forces PHP to check types as well.
Related
I am sending x = false; Boolean value through the POST method. Will Request::post['x'] or $_POST['x'] return Boolean false or null?
If I try (!isset($_POST['x'])) it gives me true, but I don't understand why.
Note that using ! (the NOT logical operator), means that (!isset($_POST['x'] )) will return true if x is not set (i.e. null).
All data in $_POST is untyped; it is all a string. If you need to send Boolean values, one option would be to compare a string to "true" or "false".
if ($_POST['x'] === "true") {
// True
} elseif ($_POST['x'] === "false") {
// False
} else {
// Error - not equal to true or false string
}
A note regarding comparison operators in PHP:
$x == $y returns true if $x is equal to $y
$x === $y returns true if $x is equal to $y and they are of the same type
If $_POST['x'] will contain anything, except null, then isset() will return true.
What is the difference, specifically in PHP? Logically they're the same (or so seem), but is there any advantage with one over the other? Including micro-benchmarking if any difference.
Example code:
$a = fc();
// Example 1
if (!$a) echo "Ex. 1";
// Example 2
if (false === $a) echo "Ex. 2";
// Example 3
if (true !== $a) echo "Ex. 3";
function fc()
{
return false;
}
!
Just invert your result value (boolean or not) from true to false or false to true
Example:
if (!file_exists('/path/file.jpg')) {
// if file NOT exists
}
=== false (or true)
The value compared MUST BE a boolean false or true.
Example:
$name = 'Patrick Maciel';
if ($name === true) {
// not is, because "Patrick Maciel" is a String
}
BUT if you do that
if ($name == true) {
// it is! Because $name is not null
// and the value is not 'false': $name = false;
}
In this case, this operator is just for check that:
$connection = $this->database_connection_up();
if ($connection === true) {
echo 'connected to database';
} else {
echo 'error in connection';
}
$valid_credit_card = $this->validate_credit_card($information);
if ($valid_credit_card === false) {
echo 'Your credit card information is invalid'
}
!== true (or false)
It's the same thing. Only the opposite of ===, ie: the value cannot be a boolean true or false.
Sorry for my english.
The difference boils down to type juggling. The ! operator converts a value to its boolean value, then inverts that value. === false simply checks if the value is, in fact, false. If it's not false, the comparison will be false.
If the value being compared is guaranteed to be a boolean, these operations will behave identically. If the value being compared could be a non-boolean, the operations are very much different. Compare:
php > $a="0";
php > var_dump(!$a);
bool(true)
php > var_dump($a === false);
bool(false)
php > $a = false;
php > var_dump(!$a);
bool(true)
php > var_dump($a === false);
bool(true)
I have a variable that can be int or bool, this is because the db from where im querying it change the variable type at some point from bool to int, where now 1 is true and 0 is false.
Since php is "delicate" with the '===' i like to ask if this is the correct why to know if that var is true:
if($wallet->locked === 1 || $wallet->locked === true)
I think in this way im asking for: is the type is int and one? or is the var type bool and true?
How will you approach this problem?
Your code is the correct way.
It indeed checks if the type is integer and the value is 1, or the type is boolean and the value is true.
The expression ($x === 1 || $x === true) will be false in every other case.
If you know your variable is an integer or boolean already, and you're okay with all integers other than 0 evaluating to true, then you can just use:
if($wallet->locked) {
Which will be true whenever the above expression is, but also for values like -1, 2, 1000 or any other non-zero integer.
$wallet->locked = 1;
if($wallet->locked === true){
echo 'true';
}else{
echo 'false';
}
will produce:
false
and
$wallet->locked = 1;
if($wallet->locked == true){
echo 'true';
}else{
echo 'false';
}
will produce:
true
Let me know if that helps!
Your solution seems to be perfect, but You can also use gettype. After that You can check the return value with "integer" or "boolean". Depending on the result You can process the data the way You need it.
solution #1. If $wallet has the value of either false or 0, then PHP will not bother to check its type (because && operator is short-circuit in PHP):
$wallet = true;
//$wallet = 1;
if( $wallet && (gettype($wallet) == "integer" || gettype($wallet) == "boolean") )
{ echo "This value is either 'true and 1' OR it is '1 and an integer'"; }
else { echo "This value is not true"; }
solution #2 (depending on what You want to achieve):
$wallet = 0;
//$wallet = 1; // $wallet = 25;
//$wallet = true;
//$wallet = false;
if($wallet)
{ echo "This value is true"; }
else { echo "This value is not true"; }
What does an exclamaton mark in front of a variable mean? And how is it being used in this piece of code?
EDIT: From the answers so far I suspect that I also should mention that this code is in a function where one of the parameters is $mytype ....would this be a way of checking if $mytype was passed? - Thanks to all of the responders so far.
$myclass = null;
if ($mytype == null && ($PAGE->pagetype <> 'site-index' && $PAGE->pagetype <>'admin-index')) {
return $myclass;
}
elseif ($mytype == null && ($PAGE->pagetype == 'site-index' || $PAGE->pagetype =='admin-index')) {
$myclass = ' active_tree_node';
return $myclass;
}
elseif (!$mytype == null && ($PAGE->pagetype == 'site-index' || $PAGE->pagetype =='admin-index')) {
return $myclass;
}`
The exclamation mark in PHP means not:
if($var)
means if $var is not null or zero or false while
if(!$var)
means if $var IS null or zero or false.
Think of it as a query along the lines of:
select someColumn where id = 3
and
select someColumn where id != 3
! negates the value of whatever it's put in front of. So the code you've posted checks to see if the negated value of $mytype is == to null.
return true; //true
return !true; //false
return false; //false
return !false; //true
return (4 > 10); //false
return !(4 < 10); //true
return true == false; //false
return !true == false; //true
return true XOR true; //false
return !true XOR true; //true
return !true XOR true; //false
! before variable negates it's value
this statement is actually same as !$mytype since FALSE == NULL
!$mytype == null
statement will return TRUE if $mytype contains one of these:
TRUE
number other than zero
non-empty string
elseif (!$mytype == null && ($PAGE->pagetype == 'site-index' || $PAGE->pagetype =='admin-index')) {
return $myclass;
}
The above !$mytype == null is so wrong. !$mytype means that if the variable evaluates to false or is null, then the condition will execute.
However the extra == null is unnecessary and is basically saying if (false == null) or if (null == null)
!$variable used with If condition to check variable is Null or Not
For example
if(!$var)
means if $var IS null.
I've been writing my "If this variable is not empty" statements like so:
if ($var != '') {
// Yup
}
But I've asked if this is correct, it hasn't caused a problem for me. Here is the answer I found online:
if (!($error == NULL)) {
/// Yup
}
This actually looks longer than my approach, but is it better? If so, why?
Rather than:
if (!($error == NULL))
Simply do:
if ($error)
One would think that the first is more clear, but it's actually more misleading. Here's why:
$error = null;
if (!($error == NULL)) {
echo 'not null';
}
This works as expected. However, the next five values will have the same and (to many, unexpected) behavior:
$error = 0;
$error = array();
$error = false;
$error = '';
$error = 0.0;
The second conditional if ($error) makes it more clear that type casting is involved.
If the programmer wanted to require that the value actually be NULL, he should have used a strict comparison, i.e., if ($error !== NULL)
It is good to know exactly what is in your variable, especially if you are checking for uninitialized vs null or na vs true or false vs empty or 0.
Therefore, as mentioned by webbiedave, if checking for null, use
$error !== null
$error === null
is_null($error)
if checking for initilized, as shibly said
isset($var)
if checking for true or false, or 0, or empty string
$var === true
$var === 0
$var === ""
I only use empty for ''s and nulls since string functions tend to be inconsistent. If checking for empty
empty($var)
$var // in a boolean context
// This does the same as above, but is less clear because you are
// casting to false, which has the same values has empty, but perhaps
// may not one day. It is also easier to search for bugs where you
// meant to use ===
$var == false
If semantically uninitialized is the same as one of the values above, then initialize the variable at the beginning to that value.
$var = ''
... //some code
if ($var === '') blah blah.
Why just don't
if (!$var)
There are ways:
<?php
error_reporting(E_ALL);
$foo = NULL;
var_dump(is_null($inexistent), is_null($foo));
?>
Another:
<?php
$var = '';
// This will evaluate to TRUE so the text will be printed.
if (isset($var)) {
echo "This var is set so I will print.";
}
?>
To check if it's empty:
<?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';
}
?>