I have this code
if (true == $run_user['online'] {
$result = 'Online now!';
} else {
$date = $run_user['lastloggedin'];
$result = Agotime($date);
}
$run_user is to check the database by the way
So whenever I change the value in the database to false, it will still just result "Online Now!" Instead of saying what it's supposed to say, which is for example 1 hour ago.
#John Conde had it right, but I can expound on what is actually happening.
In PHP there are certain things that will be left for interpretation. Boolean checks are one of those things. Here is a couple lists of things that will be interpreted in a Boolean check:
These will be interpreted as TRUE
Boolean true, of course
Non-empty strings
Any non-zero integer
A function, object or array
These will be interpreted as FALSE
Boolean false
The integer 0
An empty string
null
The not (!) character followed by an interpreted true or Boolean true
These might be confusing at times, but the best thing to do for checking is to make sure you know what type of variables you are passing into the conditional. Sometimes it may be useful to use a strict comparator like so:
if(true === $variable){ ... }
The third equal sign will tell PHP to only interpret this as true/false if it is EXACTLY what I am comparing it to. So $variable = true; would work, but $variable = 1; would not. Without the strict comparator, both versions would work. This issue comes into play a lot when you are working with integers where 0 needs to be interpreted as true and null should be false.
Related
So the syntax for if statements is:
if(condition){
//code to execute
}
Then why do functions when placed in place of conditions work in PHP.
In PHP (and many languages) there is no specific concept of a "condition"; the actual definition of an if statement is:
if(expression){
//code to execute
}
An "expression" is simply anything that can be evaluated and results in a value. A single value, like 42 is an expression on its own, as is a simple sum like 1 + 1. A function call like strlen('hello') is also an expression, evaluating to the result of the function; the function has to be run, which may have side effects, to determine that result. Expressions can be arbitrarily complex by linking then with operators, like strlen('hello') * 2 + 1.
Commonly in an if statement, you'd have something like $foo === $bar - this is just an expression that uses the === operator to give a boolean result, either true or false. PHP will evaluate that expression, and then decide whether to run the conditional code based on the result. The expression can be as simple or complex as you want - if(true) is valid, though not often useful, and so is if((strlen('hello') * 2 + 1) > 10).
If the result of the expression is not a boolean, PHP "coerces" it into one, as described on the manual page about the boolean type. For instance strlen($foo) evaluates to an integer, and all integers other than zero coerce to true, so if(strlen($foo)) acts like if(strlen($foo) !== 0).
As well as function calls, there are other expressions which have side effects. For instance, an assignment can also be used as an expression, evaluating to the value assigned. This lets you do things like $foo = $bar = 0; where $foo is assigned the result of running $bar = 0; which is of course 0. It also lets you put assignments inside if statements, like if ( $result = getData() ) { ... }, which is shorthand for $result = getData(); if ( $result ) { ... } This technique should be used with care, though, because at a glance it can be hard to spot the difference between = (assignment) and == (weak comparison).
The values returned in a PHP if condition are not restricted to be "strictly" Boolean, however the condition is expected to be Boolean. Why? Because all PHP variables types (inbuilt or user-defined) can be implicitly type-casted (converted automatically) to Boolean. According to the PHP manual:
To explicitly convert a value to bool, use the (bool) or (boolean) casts. However, in most cases the cast is unnecessary, since a value will be automatically converted if an operator, function or control structure requires a bool argument.
The PHP manual also explicitly specifies the falsy values for the different variable types including user defined types with all other values not specified being truthy:
the following values are considered false:
the boolean false itself
the integer 0 (zero)
the floats 0.0 and -0.0 (zero)
the empty string, and the string "0"
an array with zero elements
the special type NULL (including unset variables)
SimpleXML objects created from attributeless empty elements, i.e. elements which have neither children nor attributes.
Every other value is considered true (including any resource and NAN).
Therefore, to explicitly answer your question:
why do functions when placed in place of conditions work in PHP?
One reason I know of, is so you can conveniently perform assignments in the conditions:
function inverse_power($base, $exp)
{
if($power = pow($base, $exp)) {
return 1/$power;
}
else {
return "logical error: you can't divide by zero";
}
}
echo inverse_power(2,1); // 0.5
echo inverse_power(0,1); // logical error: you can't divide by zero
From the above example, you see the feature saves me multiple lines of code. Note that $power is not explicitly Boolean, but will be automatically converted to Boolean only to test the condition. The actual value of $power still persists throughout the function.
Because a condition is a boolean and functions can return booleans. And for conditions to work, the condition itself has to be evaluated, so it can be a function that is executed also.
Following are two line of code, please observe them.
$client->setWatermarkInBackground('True');
$client->setWatermarkInBackground(True);
From the code lines you might have an idea that I want to send a value True as an argument.
But I'm not getting the difference between above two statements. Can anyone explain me the difference between two statements and which one is correct or wrong? If both the ways are correct then which statement is better to use? etc. Please explain me. Thanks in advance.
$client->setWatermarkInBackground('True');
You're setting the value true as a string and not the correct Boolean.
You should set it like this (2nd method) as to set boolean ( 0/1 ).
$client->setWatermarkInBackground(True);
Allowing you to do something like:
if($client->setWatermarkInBackground()) {
// is true do whatever you need?
}
There is no difference, since PHP promotes the undefined name True to the string "True". You should instead be using the lowercase literal true
'True' is the string True, in english.
True is the boolean value that means true for the computer.
Although PHP is very good and understands both as the computer value, there are some differences:
When using the test if ($client->getWatermarkInBackground() === true), the first line will return false, because the triple = means "Same value and same type", which is not the case, a string doesn't equal a boolean.
When displaying it with echo $client->getWatermarkInBackground(), the second line will return 1, because it's how the computer understands the value true.
Which one to choose? Well, speak to the computer in its language, it's better, mostly for the programmer who will look at your code (or yourself): if you use 'True', I understand you want to display the string, if you use true, I understand you want to use it in some test later on.
Most functions you will see in PHP are smart enough to parse strings; therefore, when you pass "True" to a function, it will parse it and evaluate it as a boolean value, true.
However, this is bad practice and can cause some errors.
If you want to be correct in all cases, do not use any quotes.
true --> boolean value
"true" --> string
Edit
According to php.net,
var_dump((bool) "false"); // bool(true)
Casting from "false" to a boolean value will give you a true boolean value, therefore, you must be very careful; remember that the only thing that will cast to a boolean value false is the number 0 or an empty object.
Therefore, in all cases where possible, you should use true, with no quotes.
Any string will always evaluate to true (i.e. a string is a non zero value). Therefore "false" is also true, strictly speaking. Essentially, by using "true", you are evaluating to true almost by luck.
Stick with
function(true) and function(false)
Instead of
function("true") and function("false")
I see a lot of people using a variety of different methods to check whether of a variable is empty, there really seems to be no consensus. I've heard that if($foo) is exactly the same as if(!empty($foo)) or if($foo != ""). Is this true?
I realize it's a really simple question, but I'd really like to know. Are there any differences? Which method should I use?
Difference between bare test and comparison to empty string
if($foo != "") is equivalent to if($foo) most of the time, but not always.
To see where the differences are, consider the comparison operator behavior along with the conversion to string rules for the first case, and the conversion to boolean rules for the second case.
What I found out is that:
if $foo === array(), the if($foo != "") test will succeed (arrays are "greater than" strings), but the if($foo) test will fail (empty arrays convert to boolean false)
if $foo === "0" (a string), the if($foo != "") test will again succeed (obviously), but the if($foo) test will fail (the string "0" converts to boolean false)
if $foo is a SimpleXML object created from an empty tag, the if($foo != "") test will again succeed (objects are "greater than" strings), but the if($foo) test will fail (such objects convert to boolean false)
See the differences in action.
The better way to test
The preferred method to test is if(!empty($foo)), which is not exactly equal to the above in that:
It does not suffer from the inconsistencies of if($foo != "") (which IMHO is simply horrible).
It will not generate an E_NOTICE if $foo is not present in the current scope, which is its main advantage over if($foo).
There's a caveat here though: if $foo === '0' (a string of length 1) then empty($foo) will return true, which usually is (but may not always be) what you want. This is also the case with if($foo) though.
Sometimes you need to test with the identical operator
Finally, an exception to the above must be made when there is a specific type of value you want to test for. As an example, strpos might return 0 and also might return false. Both of these values will fail the if(strpos(...)) test, but they have totally different meanings. In these cases, a test with the identical operator is in order: if(strpos() === false).
No it's not always true. When you do if($foo) PHP casts the variable to Boolean. An empty string, a Zero integer or an empty array will then be false. Sometimes this can be an issue.
You should always try to use the most specific comparison as possible, if you're expecting a string which could be empty use if($foo==='') (note the three equal signs). If you're expecting either (boolean) false or a resource (from a DB query for instance) use if($foo===false){...} else {...}
You may read the documentation about casting to boolean to find the answer to this question. There's a list in there with which values are converted to true and false, respectively.
Note that empty also checks if the variable is set, which regular comparison does not. An unset variable will trigger an error of type E_NOTICE during comparison, but not when using empty. You can work around this using the isset call before your comparison, like this:
if(isset($foo) && $foo != '')
if() "converts" the statement given to a bool, so taking a look at the documentation for boolean seems to be what you're looking for. in general:
empty strings (""), empty arrays (array()), zero (0) and boolean false (false) are treated as false
everything else ("foo", 1, array('foo'), true, ...) is treated as true
EDIT :
for more information, you could also check the type comparison tables.
empty($foo) should return true in all of these cases: 0,"", NULL.
For a more complete list check this page: http://php.net/manual/en/function.empty.php
No, it's not equal. When variable is not defined, expression without empty will generate notice about non-defined variable.
I'm pretty sure this is a simple fundamental flaw in my newb PHP knowledge, but I was surprised when the following happened:
$result is TRUE... so why is it considered equal to the string "email"? I'm guessing this is because, technically, it's a bool and it isn't false? So when it's compared against a string (e.g. "email") it returns true.
Should I change my method to return as the result as a string containing "true" (instead of return true; on success), or is there another way I should be doing this?
Thanks.
Yes, true is equal (==) to a non-empty string. Not identical (===) though.
I suggest you peruse the type comparison table.
It returns true because php will try to convert something to be able to compare them. In this case it probably tries to convert the string on the right side to a bool which will be true in this case. And true == true is ofcourse true.
By doing $result === "email" (triple =) you tell PHP that it shoudn't do conversions and should return false if the types don't match.
if($result === "email") will do the trick but personally I would never go this way.
I was studying some code I found on the web recently, and came across this php syntax:
<?php $framecharset && $frame['charset'] = $framecharset; ?>
Can someone explain what is going on in this line of code?
What variable(s) are being assigned what value(s), and what is the purpose of the && operator, in that location of the statement?
Thanks!
Pat
Ah, I just wrote a blog post about this idiom in javascript:
http://www.mcphersonindustries.com/
Basically it's testing to see that $framecharset exists, and then tries to assign it to $frame['charset'] if it is non-null.
The way it works is that interpreters are lazy. Both sides of an && statement need to be true to continue. When it encounters a false value followed by &&, it stops. It doesn't continue evaluating (so in this case the assignment won't occur if $framecharset is false or null).
Some people will even put the more "expensive" half of a boolean expression after the &&, so that if the first condition isn't true, then the expensive bit won't ever be processed. It's arguable how much this actually might save, but it uses the same principle.
&& in PHP is short-circuited, which means the RHS will not be evaluated if the LHS evaluates to be false, because the result will always be false.
Your code:
$framecharset && $frame['charset'] = $framecharset;
is equivalent to :
if($framecharset) {
$frame['charset'] = $framecharset;
}
Which assigns the value of $framecharset as value to the array key charset only if the value evaluates to be true and in PHP
All strings are true except for two: a string containing nothing at all and a string containing only the character 0