php boolean help - php

I seem to have a small problem, in the code below $a_trip is always true, even if $trip!= $admin_trip. Any idea why?
if($trip == $admin_trip)
$a_trip = true;
if($a_trip == true)
$trip = ("~::##Admin##::~");

In PHP, strings and numbers other than zero will evaluate as true. Make sure that $a_trip is false or empty, or use the equality operator that evaluates type:
if($a_trip === true)

PHP's normal equality is very lax, and considers many values to be the same even when types are different.

Beat me to it. === means 'identical'.
Check this out.
http://php.net/manual/en/language.operators.comparison.php
Also a sidenote, you should use { } in your if statements. You'll thank yourself later when debugging. It's easier to read.

Related

Why do some people put the value before variable in if statement?

For example, what's different from $variable === true?
<?php
if (true === $variable) {
//
}
if (1 === intval($variable)) {
//
}
They are equivalent.
Some programmers prefer this "Yoda style" in order to avoid the risk of accidentally writing:
if ($variable = true) {
// ...
}
, which is equivalent to
$variable = true;
// ...
, when they meant to write
if ($variable === true) {
// ...
}
(whereas if (true = $variable) would generate an obvious error rather than a potentially-subtle bug).
Short answer
Some people do it in order to avoid mistakenly using the assignment operator (=) when they really meant to use a comparison operator (== or ===).
Long answer
In PHP there are 3 operators that can be mistaken for eachother:
= is the assignment operator
== is the "equal to" operator
=== is the "identical to" operator
The first operator is only used for assigning a value to a variable. The second and third are only used for comparing two values, or expressions, against eachother.
In PHP it is possible to assign a value to a variable inside control structures (if, for, while, etc.). This may cause problems if you are not careful. For example, if you want to compare $a against a boolean value you can do it like this:
if ($a == false) // or
if ($a === false)
If you are not careful, however, it may end up like this:
if ($a = false)
... which is perfectly legal code, but it is an assignment and will eventually cause problems. The reason it will cause problems is because the expression, $a=false, will be evaluated and the code will keep running as if nothing is wrong, when in fact it was not intended.
The reason some people switch around the operands, when comparing a value against a literal (fixed value, like true, false, 7, 5.2, and so on), is because it is not possible to assign a value to a literal. For example:
if (false = $a)
... will cause an error, telling the programmer that they made a mistake, which they can then fix.
I guess this is just the way of thinking in general. When you really think about a deep if statement, you think if that statement is true, not the other point of view. It's not wrong, but in my head naming it inverse, would annoy me and make me lose concentration about the statement. So I would say it's just the way people think :D.
There is no difference between ($var === true) and (true === $var). They are equivalent.
See http://php.net/manual/en/types.comparisons.php for a complete table of comparisons. You'll see that all equivalent comparisons have the same result.
Also, some people do prefer to see what's the result which is been evaluated before the statement.
Some statements might be longer and harder to read.
Ex:
if (false == (new DataParser()->makeAComplexDataParser((new SomeTransformer()->doTransformation((new someClass()->getMethodOfLongParameters($param1, $param2, (new Date()->format('Y-m-d')))))))) ) {
// do stuff
}
So it's better to think "is it false this complex expression?" instead of thinking
"this looooooooonger complex expression is....hmmmm....false?"

Is it safe to always use === in PHP?

I'm new to PHP and I just ran across a day-wasting bug because I didn't realize that the PHP == operator does type coercion similar to Javascript.
I know that Douglas Crockford recommends never using the == operator with Javascript, and to always use the === operator.
If I code in a manner that never assumes type coercion, can I use the same advice in PHP, and never use the == operator? is it safe to always use the === operator, or are there gotchas that I need to be aware of?
You should use === by default (to avoid the problems you just encountered) and use == when needed, as a convenience.
For instance, you may be taking parameters from $_GET or similar, and a parameter might be the string true or false, vs the boolean true or false. Personally, I check everything, but there can be legitimate use cases for == if you are conscious of it, and careful with use.
== and ===, exist for specific reasons. As you've already mentioned in your post, == does type coercion.
I come from a strongly typed programming background, and thus never require type coercion, quite like you. In this case, it is safe to always use ===.
Of course, when you do require coercion, use ==.
In case of inputs you have no control over (GET/POST parameters, API responses) you could either use == or use casting.
var_dump('1' == 1); return bool(true) and var_dump('1' === 1); return bool(false) because they have the same value but different types. One is string and other is int.
Only use === if you know the type you are checking.

String compare on a bool

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.

What's the difference between those PHP if expressions?

What's the difference between those PHP if expressions!?
if ($var !== false)
{
// Do something!
}
if (false !== $var)
{
// Do something!
}
Some frameworks like Zend Framework uses the latest form while the traditional is the first.
Thanks in advance
The result of the expression is the same however it's a good way of protecting yourself from assigning instead of comparing (e.g writing if ($var = false) instead of if ($var == false), since you can't assign the value $var to the false keyword)
It's just a preference really. You can put it either way, a == b or b == a, but it's easier to make a mistake if you do
if ($var == false)
because if you accidentally type it with one = letter, the condition will always equal to true (because $var will be set successfully), but in case of
if (false == $var)
if you now put in =, you will get an error.
The two expressions are semantically identical. It's just a matter of preference whether to put the constant expression first or last.
There's no real difference. The operands are just on different sides but the comparison is the same nonetheless.
There is no difference. !== compares 2 expressions with type checking, and returns true if they are not equal. The difference may be in the evaluation order of the expressions, but in the case you wrote, there is no difference (and a good program must not rely on the execution order of such expressions).
Consider this scenario:
if (strpos($string, $substring)) { /* found it! */ }
If $substring is found at the exact start of $string, the value returned is 0.
Unfortunately, inside the if, this evaluates to false, so the conditional is not executed.
The correct way to handle that will be:
if (false !== strpos($string, $substring)) { /* found it! */ }
Conclusion:
false is always guaranteed to be false. Other values may not guarantee this. For example, in PHP 3, empty('0') was true, but it changed to false later on.

How can I have PHP avoid lazy evaluation?

I have an interesting question about the way PHP evaluates boolean expressions. When you have, for example,
$expression = $expression1 and $expression2;
or
if ($expression1 and $expression2)
PHP first checks if $expression1 evaluates to true. If this is not the case, then $expression2 is simply skipped to avoid unnecessary calculations. In a script I am writing, I have:
if ($validator->valid("title") and $validator->valid("text"))
I need to have the second statement ($validator->valid("text")) evaluated even if the first one evaluates to false. I would like to ask you whether there is some easy way to force PHP to always evaluate both statements. Thank you!
$isValidTitle = $validator->valid("title");
$isValidText = $validator->valid("text");
if($isValidTitle && $isValidText)
{
...
}
Will that suit?
This is known as short circuit evaluation, and to avoid it you need to do this, using a single &:
if($validator->valid("title") & $validator->valid("text")) {
}
Note that this is not using logical operators but actually bitwise operators:
They're operators that act on the binary representations of numbers. They do not take logical values (i.e., "true" or "false") as arguments without first converting them to the numbers 1 and 0 respectively. Nor do they return logical values, but numbers. Sure, you can later treat those numbers as though they were logical values (in which case 0 is cast to "false" and anything else is cast to "true"), but that's a consequence of PHP's type casting rules, and nothing to do with the behavior of the operators.
As such, there is some debate as to whether it is good practice to use this side effect to circumvent short-circuit evaluation. I would personally at least put a comment that the & is intentional, but if you want to be as pure as possible you should evaluate whether they are valid first and then do the if.
try to evaluate each term separately:
$term1 = $validator->valid("title");
$term2 = $validator->valid("text");
if($term1 && $term2) {
//things to do
}
This might not be the best implementation, but you could always do:
$a=$validator->valid("title");
$b=$validator->valid("text");
if($a && $b) {...}
You can define a function like:
function logical_and($x,$y) {return ($x && $y);}
Since PHP uses call-by-value, this works.
Alternatively, if you can modify the class $validator instantiates, you could make the valid method accept a string or an array. If it's an array, it runs the code that already exists on each item and only returns TRUE if all items are "valid".

Categories