What difference does variable order/side make with relational operators? - php

Compare:
if (donald_duck != null)
if (roast_potatoes > 9000)
if (love === 'explosions')
and
if (null != donald_duck)
if (9000 <= roast_potatoes)
if ('explosions' === love)
In the languages I've written in, I've always used the first order since it makes sense human-wise. e.g. "Is the parrot dead?" vs "Is dead what the parrot is?" However I've seen the (null == variable) order used a few times in various languages and places.
What operational difference does it make, and is one way more syntactically correct or widely adopted?
(I'm aware this may be different for various languages, so in particular I'm asking in regards to PHP)

There is no different in the behavior but it helps to avoid errors for example in the comparisons.
if you use obj == null to compare, you have some risk of making a mistake and putobj = null instead causing problems in your code and having unexpected results.
But if you use null == obj to compare, that risk goes away because null = obj is not a valid sentence (you can't assign an object to null) and you will receive an error in compile time.
Hope this helps

Related

php - which one is better approach null== or ==null

I saw many times that php developers use somthing like this:
if(null == $var){
}
while I use
if($var == null){
}
Are these two different? is there any reason to use each one? or it is a choice matter in any ways?
Simply null can't be assigned value
null = $a, it will throw parsing error.
but any variable can have null as value.
$a = null
So if you mistyped == to = in the second case, you have changed the value of $a and you check the if condition of the new value of $a which always evaluates to false.
Short answer, it's exactly the same thing. Long answer:
The C programming language allows assignment within the condition. e.g.
(i = 1)==1 is valid. This means that:
if (x = null)
is valid as well.
In some cases you intended to assign x = null but (most often) you just intended to compare x == null and mistyped.
Therefore developers in C (or C++) would do something like:
if (null == x)
This is because if it was mistyped to if (null = x) it would not compile.
However in PHP this is no longer a valid reason since PHP is not compiled therefore such errors are not trapped early and this defeats the whole purpose of the reversed syntax.
However, the advantage of using it in PHP is that when you do hit that part of the code, it will error instead of running normally and will therefore inform you of the problem.
On the other hand in PHP you should really use === so typos would lead to == anyway.

Should one use `if ($a != NULL)` or `if ($a !== NULL)` to control program flow?

This is perhaps a painfully basic question to answer, but I'm wondering about performance issues regarding using PHP's if identical !== versus if equal != to control flow.
Consider the following trivial PHP function:
<?php
function test_json($json = NULL) {
if ($json != NULL) {
echo 'You passed some JSON.';
} else {
echo 'You failed to pass any JSON.';
}
}
?>
From a performance standpoint, is it preferable to employ if identical (!==) to prevent PHP iterating through variable types, attempting to find a valid comparison?
I assume that !== first compares the variable types, and if that fails, it immediately returns FALSE?
I've used != since PHP3 almost as a reflex. Now that I'm working on some much more computationally-intensive projects, minute performance considerations become more of a concern.
Other comments on flow control optimization are, of course, welcome!
I haven't done any performance tests on loose vs strict comparison operators, but for what you are trying to do, I would instead recommend something like
if (!is_null($json)) {
do_stuff()
}
More information on is_null() at http://www.php.net/manual/en/function.is-null.php
EDIT: a note in the comments of the php page I linked to above has some results showing that the === operator is slightly faster than the == operator, both of which are faster than is_null(). However, another note points out that "The execution time difference between ===NULL and is_null is less than 250 nanoseconds. Go optimize something that matters." I'd have to agree there. So all that said, I would suggest you go with what you deem to be the most readable.
You could write a test code like this before asking; according to test "Using "===" is 30x quicker than is_null()."
http://www.php.net/manual/en/language.types.null.php#77937

Difference between variable === value and value === variable?

a)
if(null === $object)
{
//take some action
}
b)
if($object === null)
{
//take some action
}
I am in habit of doing like b) but in Zend-Framework I find everywhere they have done it like a) . Is there any benefits of it ??
Thanks.
No, there is no difference.
The latter is supposed to help to avoid silly typos when you write $a = null instead of $a == null (or $a === null). In first case you'll get logical error, because of assignment instead of comparison, in second case - you'll get fatal error which will help you to find an issue sooner.
There is no difference, it is used to avoid mistakes (like setting variable to null, not comparing them), however the null === $object is often considered the Bad Way (c) to avoid typos.
The $object === null expression is much more human-friendly then null === $object 'cause second one breaks nature reading order which is left-to-right. That's why even if there is no much difference for interpreter but it's a bit harder to read by a human. Involving some logic - if you use if..else statement how it should sounds like? "If null equals $object.. Wait a minute, null is null, how can it be equal to something else? Oh, Gee, we actually comparing right-handed value to left-handed one, it's reversed stuff. So, if $object equals null then we should..". And your think this way every time.
My conclusion is: use $value == const every time you can! Long time ago people wrote if ($value = const) but these times have passed. Now every IDE can tell ya about such simple errors.
b) is way more readable than a)
And a) is considered by some overcautious people as less error prone because of possible confusing == with =.
But in case of three ='s I doubt anyone will confuse it with one.
This a choice by the developer to attempt to stop accidential assignment of values.
The functionality is exactly the same between the two methods of comparison but in the case of "a" it stops any accidential assignment of values as you cannot assign something to null.
The second method checks the value and type of variable against null, The errors should be different in tow methods.

identity conditional "===" , performance, and conversion

I've always came away from stackoverflow answers and any reading I've done that "===" is superior to "==" because uses a more strict comparison, and you do not waste resources converting value types in order to check for a match.
I may be coming at this with the wrong assumption, so I assume part of this question is, "is my assumption true?"
Secondly,
I'm dealing specifically with a situation where I'm getting data from a database in the form of a string "100".
The code I am comparing is this...
if ($this->the_user->group == 100) //admin
{
Response::redirect('admin/home');
}
else // other
{
Response::redirect('user/home');
}
vs.
if ( (int) $this->the_user->group === 100) //admin
{
Response::redirect('admin/home');
}
else // other
{
Response::redirect('user/home');
}
or even
if (intval($this->the_user->group) === 100) //admin
{
Response::redirect('admin/home');
}
else // other
{
Response::redirect('user/home');
}
is any integrity (or performance) gained by manually casting or converting simply so you can use the identity ('===') comparison?
In your particular case == is the better option. As you (as can be seen in your code) have probably already found out many database functions will always return strings, even if you fetch an integer. So type strict comparison really only bloats your code.
Furthermore you are adding a potential (let's call it theoretic) security risk. E.g. (int) '100AB2' would yield 100. In your case this probably can't happen, but in others it may.
So: Don't overuse strict comparison, it's not always good. You mainly need it only in ambiguous cases, like the return value of strpos.
There is a performance difference between == and === - latter will be even twice as fast, see Equal vs identical comparison operator.
The difference, however is too small to be bothered with - unless the code is executed millions of times.
That's a really tiny optimization you're doing there. Personally, I don't think it's really worth it.
Any boost you gain from not casting the value when using === is lost when you explicitly cast the value. In your case, since the type is not important to you, you should just do == and be done with it.
My recommendation would be to keep === for when you need to check type as well - e.g. 0 evaluating to false and so on.
Any performance gains will be microscopically small, unless you're performing literally billions and trillions of these comparisons for days/months/years on-end. The strict comparison does have its uses, but it also is somewhat of anomally in PHP. PHP's a weakly typed language, and (usually) does the right thing for auto-converting/casting values to be the right thing. Most times, it's not necessary to do a strict comparison, as PHP will do the right thing.
But there are cases, such as when using strpos, where the auto-conversion will fail. strpos will return '0' if the needle you're searching is right at the start of the haystack, which would get treated as FALSE, which is wrong. The only way to handle this is via the strict comparison.
PHP has some WTF loose comparisons that return TRUE like:
array() == NULL
0 == 'Non-numeric string'
Always use strict comparison between a variable and a string
$var === 'string'

Why isset() is more efficient to test than '==='?

Summarized, I made a loop with a few iterations to check the efficiency of each test:
$iterations = 99999999;
$var = null;
isset comparasion
if ( isset( $var ) )
{
}
'===' comparasion
if ( $var === null )
{
}
And i have this log, in microseconds:
'isset()': 1.4792940616608
'===': 1.9428749084473
For me, this is a little curious. Why isset() function is faster than one comparison operator as ===?
The === comparison is a strict check, meaning that the two objects you're comparing have to be of the same type. When you break it down in plain English, it's actually not that weird that === needs some more time. Consider the parser to do this:
if (isset($var)) {
// Do I have something called $var stored in memory?
// Why yes, I do.. good, return true!
}
if ($var === null) {
// Do I have something called $var stored in memory?
// Why yes, I do.. good! But is it a NULL type?
// Yes, it is! Good, return true!
}
As you can see, the === operator needs to do an additional check before it can determine if the variable matches the condition, so it's not that strange that it is a little bit slower.
Isset is not a function: it is a language built-in. Using isset is faster than using a function.
The other thing is that isset is used all over the place, so it makes sense that it's been profiled to death, whereas === maybe hasn't received as much love.
Other than that, you'd have to dig in the PHP source with a profiler to see exactly what's going on.
I'm not sure I would call 100 million "a few iterations". You appear to have accumulated about a half-second difference, divide that by 100 million and you get a whopping 5 nanosecond difference per iteration if my math is correct. With the difference being so small it may simply come down to the fact that isset only has one operand in this context and === has two.
It's impossible to even discuss the Zend engine's implementation details of the two examples without specifying a specific PHP version; source code is a moving target. Even minute changes to the implementations are going to effect the results over that many passes. I would not be surprised if you found the opposite to be the case on some versions of PHP and/or in a different context.
isset itself is covered by three different op-codes in the VM depending upon the context:
"Simple" Compiled Variables like your example: ZEND_ISSET_ISEMPTY_VAR
Arrays: ZEND_ISSET_ISEMPTY_DIM_OBJ (requires 2 operands, the var and the index)
Object properties: ZEND_ISSET_ISEMPTY_PROP_OBJ (also 2 operands, var and prop name)
It's an interesting question for curiosity's sake but we're in hair splitting territory and it's probably not a real-world optimization strategy.

Categories