Difference between "&&" and "and" : Operator precedence and short circuiting - php

I was going through operator precedence section of php.net and came across this example which says
$a = 1;
$b = null;
$c = isset($a) && isset($b);
$d = ( isset($a) and isset($b) );
$e = isset($a) and isset($b);
var_dump($a, $b, $c, $d, $e);
//Result:
int(1)
NULL
bool(false)
bool(false) <== I get this
bool(true) <== I do not get this
I use quite a lot of debugging and verbose print(_r) statements in my code to keep track of where I am in the code. So I use $debug and print_r($dataArray) or $verbose and print "Updating dataArray\n" as separate statements in between the code, allowing me to control these print(_r) statements. This comes from my BASH experience where I used to write lot of [[ $condition ]] && { #Do if true } || { #Do if false }. In BASH, I knew they are short circuited and used this fact to write lot of simple one liners.
Now I am observing that lot of this practice(of writing $verbose and print) is slowly creeping into my if statements. I am aware this is NOT a recommended practice and can bite me in the back. However, I do want to master this skill as I enjoy writing such one liners and want to use it as my personal style.
So my question(s) is(are) :
Which operator (&& or and) is short circuited ?
The manual says && takes precedence over and, but can someone exemplify this by mixing the short circuited operator feature/functionality/characteristic with operator precedence. (basically mix and match of precedence and short-circuiting)
Kindly elaborate on both the short-circuiting as well as return value nature of the operators.
PS: 1. I hope associativity of these operators is same and intuitive, but if you know any quirks, please enlighten me.
PS: 2. If you still feel like warning me against the perils of such practice, kindly include examples.
EDIT : After changing my simple $var = mysql_(...) or die() code by replacing or with ||, I discovered how annoying it can be to use the || and && operators instead of and and or. The code simply didn't work ! To my understanding, the former construct assigns a return value of TRUE or FALSE to $var, which in turn make all sequential use of $var to generate warning/error/unexpected behavior. The latter construct assigns result of mysql_(...) to $var first and then evaluates the compound of = and die.
This is a good lesson for me, I better 1. Start using PDO/mysqli and handle errors on my own 2. Think twice before writing something I called above as personal style.
//note to self : don't use experience of one scripting/interpretive language while writing code in another, each one is unique and has its own quirks and pitfalls, and thats just sad *sigh*

The code
$e = isset($a) and isset($b);
is parsed the same as
($e = isset($a)) and isset($b);
Therefore $e, as determined by isset($a) and the assignment, is true - independent of evaluating isset($b).

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?"

logical operator that returns operands in PHP

In any "sane" programming language, from C to Javascript, an expression such as a || b (or a or b) evaluates to a if a is true and to b otherwise, making possible things like a = params.a || default_a and similar for the and operator, but PHP begs to differ.
Is there any way to get this in PHP? Or is there any "coding idiom/pattern" that PHP programmers use instead of something like the code below?
$a = $my_a || $default_a; // nope, $a gets a boolean
Because writing if ($my_a) $a = $my_a; else $a = $default_a; or $a = $my_a ? $my_a : $default_a; seems very ugly to me and violates basic "DRY-ness" of code by making me repeat something like $my_a, which can also be a very long and complicated expression.
It's a minor thing, I know, and not that singular in the land of the double clawed hammer but it really annoys the hell outta me!
Worth to mention: It's C and Javascript, that makes the difference, because "in a 'sane' language" (;)) the return value of a boolean operation is a boolean and not one of its operands.
However
$a = $my_a ?: $default_a;

Is there difference between ternary operator and if condition?

Is there difference between ternary operator and if condition in php ?
if yes, kindly provide.
The ternary operator is an operator, so it forms an expression. So it will have a value that you can assign to a variable or use however you want. It is used for simple situations where a variable can take two possible values depending on a condition.
For example: $status = $age > 18 ? 'adult' : 'child';
Although possible, you should not nest the ternary operator.
The control structure if is something absolutely different. The only thing they have in common that both evaluate a condition (true/false). if is used to execute code fragments based on the result of that condition. You will find yourself using if most of the time (in fact, you can live without the ternary). In certain situations, it is less code and more readable if you replace certain types of ifs with the ternary, like this one:
if ($age > 18) {
$status = 'adult';
} else {
$status = 'child';
}
Personally, I only use the ternary operator if it fits on one line. If it need to span, then it's time for the good old
$value = ($a < 0) ? 'minus' : 'plus';
also you can see one interesting question how multiple ternary works :
unusual ternary operation
If statements are faster than ternary, but in most cases it doesn't matter.
Here is a post on the performance of If statements vs ternary.
Summary: It's basically the same unless you are evaluating large objects because ternary copies the objects being evaluated. This was using PHP 5.3 I'm not sure if it has been changed in current versions.
The ternary operator can do anything that an if/else statement can. In some cases it can provide brevity and expressiveness, but beware: it is easily abused.
One thing I like it for is checking for null:
$foo = (is_null($bar)) ? 0 : $bar->someNumber();
If my PHP memory serves me correctly, then it can also be used on an lvalue:
((is_null($foo)) ? $bar : $foo) = $quux;
It can be easily overdone though, such as in this C++ example, where it is used in place of loops and if/else statements:
while( ( ! printingStars) ?
( ( ! reachedMax) ?
( ( ++numberOfStars == n - 1) && (reachedMax = 1) )
: --numberOfStars ), printingStars = 1, starsLeft = numberOfStars
: ( ( ! starsLeft ) ?
printingStars = 0, (std::cout<< std::endl), 1
: --starsLeft, (std::cout<< "*"), 1 ) );
Use with caution.
Maybe another point of view: Performance.
A while ago I noticed that the ternary operator is faster than an if(). I don't know if this still applies to the latest versions of PHP.
< wild guess >
The reason may be that an if() allows more flexibility like using code blocks ({ }). A ternary operator basically is just testing an expression and grabbing a value depending on the result of the test.
Going back into my Assembler-days I'd say that an if() has to jump in memory and, therefore, takes a bit more time to do things.
< /wild guess >
However, this may be become noticeable only if the code is executed a decent number (1k+) of times.
There is a big difference in maintenance, if you use none trivial logic.
If you have a difficult problem you need under circumstances much more time, to sove it, as if you have an 'if ... then' in your code. And be sure: it's happen!
The time is not a friend of ternary operator. Fast to write, but not fast to understand, if the years gone!

PHP - and / or keywords

Is && the same as "and", and is || the same as "or" in PHP?
I've done a few tests, and it seems they behave the same. Are there any differences?
If not, are there any other PHP signs that have word equivalents and do you think it makes the code easier to read?
and and or have higher lower precedence than && and ||. To be more exact && and || have higher precedence than assignment operator ( = ) while and and or have lower.
http://www.php.net/manual/en/language.operators.precedence.php
Usually it doesn't make a difference, but there are cases when not knowing about this difference can cause some unexpected behaviour. See examples here:
http://php.net/manual/en/language.operators.logical.php
Yes, they are logically the same. (I believe "&&" and "||" are the preferred choice in the Zend coding standards, but I can't find any specific information on this, so it might all have been a dream. Or something.)
That said:
"&&" and "||" are of a higher precedence than "AND" and "OR" (unlikely to ever be relevant, but you never know).
A lot of other languages use "&&" and "||", rather than the textual equivalents so it might be an idea to go with this.
As long as you use your choosen set of operators consistently it doesn't really matter.
What bothers me is:
echo (false and false ? true : true);
// (empty/false)
You might guess there is only the possible output of "1" (true) as there is no case which could output a false... ...but it will be "" (false).
Using && as a operator in this case satifies at least my expectations:
echo (false && false ? true : true);
// 1
So, in some cases the usage matters significantly.
The difference is on the precedence. But not only compared with each other!
In most cases you won't mind it, but there are specific cases when you have to take one step back and look at the big picture. Take this, for example:
// The result of the expression (true && false) is assigned to $g
// Acts like: ($g = (true && false))
$g = true && false;
// The constant true is assigned to $h before the "and" operation occurs
// Acts like: (($h = true) and false)
$h = true and false;
var_dump($g, $h);
This will produce, respectively:
bool(false)
bool(true)
In other words, && has higher preference than =, which has higher precedence than and, as stated in http://php.net/manual/en/language.operators.precedence.php. (It is mentioned in other answers, but I think it's worth to detail, since a misuse can lead to logical errors)
I hope it may help you. You can find more at http://php.net/manual/en/language.operators.logical.php

What are the PHP operators "?" and ":" called and what do they do?

What are the ? and : operators in PHP?
For example:
(($request_type == 'SSL') ? HTTPS_SERVER : HTTP_SERVER)
This is the conditional operator.
$x ? $y : $z
means "if $x is true, then use $y; otherwise use $z".
It also has a short form.
$x ?: $z
means "if $x is true, then use $x; otherwise use $z".
People will tell you that ?: is "the ternary operator". This is wrong. ?: is a ternary operator, which means that it has three operands. People wind up thinking its name is "the ternary operator" because it's often the only ternary operator a given language has.
I'm going to write a little bit on ternaries, what they are, how to use them, when and why to use them and when not to use them.
What is a ternary operator?
A ternary ? : is shorthand for if and else. That's basically it. See "Ternary Operators" half way down this page for more of an official explanation.
As of PHP 5.3:
Since PHP 5.3, it is possible to leave out the middle part of the ternary operator. Expression expr1 ?: expr3 returns expr1 if expr1 evaluates to TRUE, and expr3 otherwise.
As of PHP 7.0
PHP 7 has new Null Coalesce Operator. This is the same as a ternary but is also called an "isset ternary". This also allows a set of chained ternaries that remove the need for isset() checks.
In PHP 5, if you wanted to use a ternary with a potentially non-existent variable then you would have to perform an isset() at the beginning of the ternary statement:
$result = isset($nonExistentVariable) ? $nonExistentVariable : ‘default’;
In PHP 7, you can now do this instead:
$result = $nonExistentVariable ?? ‘default’;
The Null Coalesce Operator does not work with an empty string, however, so bear that in mind. The great thing about this is you can also chain the operators for multiple checks for multiple variables, providing a sort of backup depending on whether or not each variable in the chain exists:
$user = $userImpersonatingAnotherUser ?? $loggedInUser ?? “Guest”;
In PHP, with systems where a user can login, it is not uncommon for an administrator to be able to impersonate another user for testing purposes. With the above example, if the user is not impersonating another user, and also a logged in user does not exist, then the user will be a guest user instead. Read on more if you don't understand this yet to see what ternaries are and how they are used, and then come back to this bit to see how the new PHP
How are ternaries used?
Here's how a normal if statement looks:
if (isset($_POST['hello']))
{
$var = 'exists';
}
else
{
$var = 'error';
}
Let's shorten that down into a ternary.
$var = isset($_POST['hello']) ? 'exists' : 'error';
^ ^ ^ ^ |
| then | else |
| | |
if post isset $var=this $var=this
Much shorter, but maybe harder to read. Not only are they used for setting variables like $var in the previous example, but you can also do this with echo, and to check if a variable is false or not:
$isWinner = false;
// Outputs 'you lose'
echo ($isWinner) ? 'You win!' : 'You lose';
// Same goes for return
return ($isWinner) ? 'You win!' : 'You lose';
Why do people use them?
I think ternaries are sexy. Some developers like to show off, but sometimes ternaries just look nice in your code, especially when combined with other features like PHP 5.4's latest short echos.
<?php
$array = array(0 => 'orange', 1 => 'multicoloured');
?>
<div>
<?php foreach ($array as $key => $value) { ?>
<span><?=($value==='multicoloured')?'nonsense':'pointless'?></span>
<?php } ?>
</div>
<!-- Outputs:
<span>
pointless
</span>
<span>
nonsense
</span>
-->
Going off-topic slightly, when you're in a 'view/template' (if you're seperating your concerns through the MVC paradigm), you want as little server-side logic in there as possible. So, using ternaries and other short-hand code is sometimes the best way forward. By "other short-hand code", I mean:
if ($isWinner) :
// Show something cool
endif;
Note, I personally do not like this kind of shorthand if / endif nonsense
How fast is the ternary operator?
People LIKE micro-optimisations. They just do. So for some, it's important to know how much faster things like ternaries are when compared with normal if / else statements.
Reading this post, the differences are about 0.5ms. That's a lot!
Oh wait, no it's not. It's only a lot if you're doing thousands upon thousands of them in a row, repeatedly. Which you won't be. So don't worry about speed optimisation at all, it's absolutely pointless here.
When not to use ternaries
Your code should be:
Easy to read
Easy to understand
Easy to modify
Obviously this is subject to the persons intelligence and coding knowledge / general level of understanding on such concepts when coming to look at your code. A single simple ternary like the previous examples are okay, something like the following, however, is not what you should be doing:
echo ($colour === 'red') ? "Omg we're going to die" :
($colour === 'blue' ? "Ah sunshine and daisies" :
($colour === 'green' ? "Trees are green"
: "The bloody colour is orange, isn't it? That was pointless."));
That was pointless for three reasons:
Ridiculously long ternary embedding
Could've just used a switch statement
It was orange in the first place
Conclusion
Ternaries really are simple and nothing to get too worked up about. Don't consider any speed improvements, it really won't make a difference. Use them when they are simple and look nice, and always make sure your code will be readable by others in the future. If that means no ternaries, then don't use ternaries.
It's called a ternary operator. If the first expression evaluates to true, HTTPS_SERVER is used, else HTTP_SERVER is chosen.
It's basically a shorthand if statement, and the above code could also be rewritten as follows:
if ($request_type == 'SSL') {
HTTPS_SERVER;
}
else {
HTTP_SERVER;
}
This is sometimes known as the ternary conditional operator. Ternary means that it has three arguments, as x ? y : z. Basically, it checks if x is true; if it is, then put y instead of this operation, otherwise z.
$hello = $something ? "Yes, it's true" : "No, it's false";
Conditional operator ? : is an operator which is used to check a condition and select a value depending on the value of the condition. It is expressed in the following form:
variable = condition ? expression1 : expression2;
It works as follows...
Firstly, condition is evaluated.
If the condition is true, then expression1 is evalauated. And the value of expression1 is assigned to the variable.
If the condition is false, then expression2 is evaluated. And the value of expression2 is assigned to the variable.
For example:
x = (a>b) ? 5 : 9
In this, for x, firstly the condition (a>b) is evaluated. If this condition becomes true, then x will become the value 5 (ie, x=5). But if the condition (a>b) becomes false, then x will attain the value 9 (ie, x=9).
Ternary Operator
Sometimes conditional operator ? : is also called a ternary operator. This is so because it involves three operands. For example:
x ? y : z
Here, x,y and z are the three operands. If condition x is true, then value y is assigned otherwise value z is assigned.
This is a short way of writing if sentences. It is also used in other languages like Java, JavaScript and others.
Your code,
$protocol = $request_type == 'SSL' ? HTTPS_SERVER : HTTP_SERVER;
can be written like this:
if ($request_type == 'SSL')
$protocol = HTTPS_SERVER;
else
$protocol = HTTP_SERVER;
That is a one line if statement:
condition ? true : false
Translated to an ordinary if statement in your case, that would be:
if($request_type == 'SSL') HTTPS_SERVER;
else HTTP_SERVER;
That's basically a fancy way of writing an if-else statement. Some say it's easier to read, some say not.
Ternary operator at Wikipedia
This works like an if statement it's very simple and easy once you get used to it.
(conditions_expressions) ? what_to_do_if_true : what_to_do_if_false.
As John T says, it is called a ternary operator and is essentially a shorthand version of an if /else statement. Your example, as a full if / else statement, would read;
if($request_type == 'SSL')
{
HTTPS_SERVER;
}
else
{
HTTP_SERVER;
}

Categories