This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Reference - What does this symbol mean in PHP?
Getting confused with empty, isset, !empty, !isset
In PHP what is the difference between:
if(!isset)
if(isset)
Same with if(!empty) and if(empty)?
What does the "!" character mean?
! is the logical negation or NOT operator. It reverses the sense of the logical test.
That is:
if(isset) makes something happen if isset is logical True.
if(!isset) makes something happen if isset is logical False.
More about operators (logical and other types) in the PHP documentation. Look up ! there to cement your understanding of what it does. While you're there, also look up the other logical operators:
&& logical AND
|| logical OR
xor logical EXCLUSIVE-OR
Which are also commonly used in logic statements.
The ! character is the logical "not" operator. It inverts the boolean meaning of the expression.
If you have an expression that evaluates to TRUE, prefixing it with ! causes it evaluate to FALSE and vice-versa.
$test = 'value';
var_dump(isset($test)); // TRUE
var_dump(!isset($test)); // FALSE
isset() returns TRUE if the given variable is defined in the current scope with a non-null value.
empty() returns TRUE if the given variable is not defined in the current scope, or if it is defined with a value that is considered "empty". These values are:
NULL // NULL value
0 // Integer/float zero
'' // Empty string
'0' // String '0'
FALSE // Boolean FALSE
array() // empty array
Depending PHP version, an object with no properties may also be considered empty.
The upshot of this is that isset() and empty() almost compliment each other (they return the opposite results) but not quite, as empty() performs an additional check on the value of the variable, isset() simply checks whether it is defined.
Consider the following example:
var_dump(isset($test)); // FALSE
var_dump(empty($test)); // TRUE
$test = '';
var_dump(isset($test)); // TRUE
var_dump(empty($test)); // TRUE
$test = 'value';
var_dump(isset($test)); // TRUE
var_dump(empty($test)); // FALSE
$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';
}
Edit:
here is a test case for you:
$p = false;
echo isset($p) ? '$p is setted : ' : '$p is not setted : ';
echo empty($p) ? '$p is empty' : '$p is not empty';
echo "<BR>";
$p is setted : $p is empty
Related
if(strpos("http://www.example.com","http://www.")==0){ // do work}
I'd expect this to resolve as true, which it does. But what happens when I do
if(strpos("abcdefghijklmnop","http://www.")==0){// do work}
This also passes on php 5 because as far as I can work out the strpos returns false which translates as 0.
Is this correct thinking/behaviour? If so what is the workaround for testing for that a substring is at the beginning of another string?
Yes, this is correct / expected behavior :
strpos can return 0 when there is a match at the beginning of the string
and it will return false when there is no match
The thing is you should not use == to compare 0 and false ; you should use ===, like this :
if(strpos("abcdefghijklmnop","http://www.") === 0) {
}
Or :
if(strpos("abcdefghijklmnop","http://www.") === false) {
}
For more informations, see Comparison Operators :
$a == $b will be TRUE if $a is equal to $b.
$a === $b will be TRUE if $a is equal to $b, and they are of the same type.
And, quoting the manual page of strpos :
This function may return Boolean
FALSE, but may also return a
non-Boolean value which evaluates to
FALSE, such as 0 or "". Please
read the section on Booleans for
more information. Use the ===
operator for testing the return
value of this function.
=== and !== compare type and value as shown below:
if (strpos("abcdefghijklmnop", "http://www.") !== false) {
// do work
}
strpos returns an int or boolean false. the == operator also evaluates 0 to mean false, you want to use the === operator (three equals signs) that also checks that the types being compared are the same instead of just seeing if they can be evaluated to mean the same.
so
if (strpos($hastack, $needle) === 0)
{
// the $needle is found at position 0 in the $haystack
}
0 is a possible return value from strpos when it finds a match at the very beginning. In case if the match is not found it returns false(boolean). So you need to check the return value of strpos using the === operator which check the value and the type rather than using == which just checks value.
I personally tend to use this way :
if(!strpos($v,'ttp:'))$v='http://'.$v;
or
if(strpos(' '.$v,'http'))
to avoid the "0" position then always make it a number more than 0
cheers
Why this line of code does not work in php like as in JS:
$id = [];
$id = null || [];
if (count($id)) {
echo 'd';
}
Why $id still is null instead empty array []? Therefore count() gives an error.
In PHP, logical operators like || always return a boolean, even if given a non-boolean output.
So your statement is evaluated as "is either null or [] truthy?" Since both null and an empty array evaluate to false, the result is boolean false.
There are however two operators which would do something similar to JS's ||:
$a ?: $b is short-hand for $a ? $a : $b; in other words, it evaluates to $a if it's "truthy", or $b if not (this is documented along with the ternary operator for which it is a short-hand)
$a ?? $b is similar, but checks for null rather than "truthiness"; it's equivalent to isset($a) ? $a : $b (this is called the null-coalescing operator)
<?php
// PHP < 7
$id = isset($id) ? $id : [];
// PHP >= 7
$id = $id ?? [];
As of PHP 7 and above
Null Coalesce Operator
Another helpful link
Watch out!
I find PHP's handling of empty to be highly questionable:
empty($unsetVar) == true (fabulous, no need to check isset as warning is suppressed!)
empty(null) == true
empty('') == true
All fine, until we get to this nonsense:
empty(false) == true. Wait, WHAT???
You've GOT to be kidding me. In no world should false be taken to mean the same thing as no value at all! There's nothing "empty" about a false assertion. And due to this logical fallacy, you cannot use empty to check ANY variable that might have a VALUE of false.
In my projects, I use a static method:
public static function hasValue($value) {
return isset($value) && !is_null($value) && $value !== '';
}
Of course, using this method, I no longer get the free warning suppression provided by empty, so now I'm also forced to remember to call the method above with the notice/warning suppression operator #:
if(self::hasValue(#$possiblyUnsetVar)) {}
Very frustrating.
I have an array ...
$a= array(1,2,3,4);
if (expr)
{ echo "if";
}
else
{ echo 'else';
}
When expr is ( $a = '' || $a == 'false') , output is "if" ,
but when expr is ( $a == 'false' || $a = '' ) , output is "else"
Can anyone explain why & how ordering makes a difference ??
Edit : I understand that I am assigning '' to $a. That is not the problem. The real question is : What does the expression $a = '' return? And why does reversing the order of the 2 situations switch us from the IF section to the ELSE section?
AGAIN : I UNDERSTAND I AM ASSIGNING NOT COMPARING. PLEASE ANSWER THE QUESTION AS IS.
First, never use = as a comparison operator. It is an assignment operator.
The difference is that false (as a boolean) is not the same as 'false' as a string.
Certain expressions are type juggled by PHP to evaluate somewhat differently to how you would expect.
false==""
// TRUE.
false=="false"
// FALSE.
Additionally, when you try to compare numbers to strings, PHP will try to juggle the data so that a comparison will be performed. There is a lot to it (much more than I will post here) but you would do well to investigate type juggling and various operators. The docs are a great start for this. You should also have a read of the comparison operators which go into a lot of detail about how various comparisons will work (depending on whether you use == or === for example).
With $a = '' you are setting $a to an empty string. This is the same as:
$a = '';
if($a){
echo 'if';
}
The || operator checks if the first condition is true and if it is, it continues with the code in the brackets. In PHP, if $a is set to anything, it will return true. In the second case $a does not equal the string 'false' (you are not comparing it to a boolean false even!), so it executes the code in the else part.
And Fluffeh is not entirely correct. You can use the assignment operator in an if condition very effectively, you just have to be smart about it.
$a = '' is an assignment: you have, in error, used = in place of ==. Assignment is an expression which has the value of the thing your assigning.
A single equals sign = is the assignment opporator, so $a = '' is assigning an empty string to $a not checking if it is equal to.
In your 1st example you set the value of $a to an empty string, then check if it is false. An empty tring evalutes to false in php, so the conditional is true.
In your second example, you check if $a equals false 1st (when the value of $a is an array), so the conditional is false
I also get confused how to check if a variable is false/null when returned from a function.
When to use empty() and when to use isset() to check the condition ?
For returns from functions, you use neither isset nor empty, since those only work on variables and are simply there to test for possibly non-existing variables without triggering errors.
For function returns checking for the existence of variables is pointless, so just do:
if (!my_function()) {
// function returned a falsey value
}
To read about this in more detail, see The Definitive Guide To PHP's isset And empty.
Checking variable ( a few examples )
if(is_null($x) === true) // null
if($x === null) // null
if($x === false)
if(isset($x) === false) // variable undefined or null
if(empty($x) === true) // check if variable is empty (length of 0)
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.
ISSET checks the variable to see if it has been set, in other words, it checks to see if the variable is any value except NULL or not assigned a value. ISSET returns TRUE if the variable exists and has a value other than NULL. That means variables assigned a " ", 0, "0", or FALSE are set, and therefore are TRUE for ISSET.
EMPTY checks to see if a variable is empty. Empty is interpreted as: " " (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), and "$var;" (a variable declared, but without a value in a class.
isset — Determine if a variable is set and is not NULL
$a = "test";
$b = "anothertest";
var_dump(isset($a)); // TRUE
var_dump(isset($a, $b)); // TRUE
unset ($a);
var_dump(isset($a)); // FALSE
empty — Determine whether a variable is 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';
}
?>
It is important to use the correct function / notation, not just whatever appears to work correctly. There are a few things to consider that are not mentioned in the existing answers.
Use isset to check if a variable has either not been set or has been set to null.
Use empty to check if a variable == false. null is cast to false and as with isset, no notice is thrown if the variable has not been set.
if (!$variable) or if ($variable == false) is the same as empty, except that a notice will be thrown if the variable has not been set.
if ($variable !== null) is the same as isset, except that a notice will be thrown if the variable has not been set.
NB
if (!$variable) and if ($variable !== null) perform better than their respective functions but not when notices are being generated, therefore, $variable needs to have been set. Don't suppress notices as a micro-optimisation, as this will make your code harder to debug and even suppressed notices cause a performance penalty.
Coalescing operators
If you are checking a variable so that you can assign a value to it, then you should use ??, ?: instead of if statements.
??
?? assigns a value when not equal to null.
$variable = $a ?? $b is the same as:
if (isset($a))
$variable = $a;
else
$variable = $b;
?:
?: assigns a value when not == to false.
$variable = $a ?: $b is the same as:
if ($a)
$variable = $a;
else
$variable = $b;
but remember that a notice will be generated when $a has not been set. If $a might not have been set, you can use $variable = !empty($a) ? $a : $b; instead.
check false: if ($v === false)
check null: if (is_null($v))
empty() is an evil.It is slow,and when $v queals false,0,'0',array(),'',it will return true.if you need this kind of checking,you can use if ($v).
I was just wandering the about the concept of equating the condition in PHP that is,
what could be the difference between
true == isset($variable)
and
isset($variable) == true
?
For this specific case, no difference.
The first syntax is used to prevent accidental assignment instead of comparison.
if ( true = $x ) // would yiled error
if ( $x = true ) // would work
But again, in your case, no difference.
Elaboration:
Say you want to compare a variable $x to true and do something. You could accidentally write
if ( $x = true )
instead of
if ( $x == true )
and the condition would always pass.
But if you get into the habit of writing
if ( true == $x )
these mistakes wouldn't happen, since a syntax error would be generated and you would know in advance.
There is no difference. But isset() itself returns a boolean value.
So never use
if (true == isset($variable))
Just:
if (isset($variable))
Remember that when php parses that true is actually defined and its equal to 1. Furthermore so is false and it is equal to 0. php automatically checks these for comparison with these values in an IF statement. You'll be safe using the ! operator, because its the same as if ($something == false) good luck!
Would it be Java, there was difference.
i.e.
String test = null;
if("".equals(test)){
System.out.println("I m fine..");
}
if(test.equals("")){
System.out.println("I m not fine..");
}
There is no "real" diffrences(in this case)
Between
true == isset($variable) AND
isset($variable) == true