Faux amis : small but significant details
Being "fluent" in more than a programming language can sometimes be a challenge, because there are many subtle differences between languages, some that you might overlook when ou learn the language. These subtelties can be found in things that you take for granted, ones that you will probably never bother consulting the manual about because it is so obvious.
In spoken language, there is something called "false friends" (faux amis in french). False friends are words that look very similar in two different languages, so you'd assume that they mean the same thing, yet it is not the case. For example, you might hear a french-speaking person say "my flight was retarded", which sounds quite funny to your english ears, but retardé in french would mean delayed in that context.
$a = array(1,2,3); $b = null; $c = $a || $b; var_dump($c);
var a = [1,2,3]; var b = null; var c = a || b; console.log(c);
In PHP, logical operators will always produce a boolean, no matter the types of the operands. In this case, $c contains
|| produce one of both operands :
- || produces the first operand if it is "truthy" and produces the second operand otherwise.
- && produces the first operand if it is "falsey" and produces the second operand otherwise.
var someVar = someParam || someDefaultValue;
which sets a variable to a value if it exists (provided that this value is not something falsey), and to a default value otherwise. In PHP though, you cannot do it with
||, you'd do it with a ternary operator like so:
$someVar = $someParam ? $someParam : $someDefaultValue;
It might not seem like much, but these small details sometimes can become an impediment to productivity. It's like searching for the right words in your own mother tongue when you've spoken another language for too long. Some people don't experience this problem, as they can switch back and forth seamlessly, but some people like me tend to make more errors when switching. For that reason, I try to organize my time so as to minimize the number of times I switch languages. This is not always possible though, especially in a small company like ours where its frequent that we lead many projects in parallel.