Does PHP support conjunction and disjunction natively? - php

Javascript employs the conjunction and disjunction operators.
The left–operand is returned if it can be evaluated as: false, in the case of conjunction (a && b), or true, in the case of disjunction (a || b); otherwise the right–operand is returned.
Do equivalent operators exist in PHP?

PHP supports short-circuit evaluation, a little different from JavaScript's conjunction. We often see the example (even if it isn't good practice) of using short-circuit evaluation to test the result of a MySQL query in PHP:
// mysql_query() returns false, so the OR condition (die()) is executed.
$result = mysql_query("some faulty query") || die("Error");
Note that short-circuit evaluation works when in PHP when there is an expression to be evaluated on either side of the boolean operator, which would produce a return value. It then executes the right side only if the left side is false. This is different from JavaScript:
Simply doing:
$a || $b
would return a boolean value TRUE or FALSE if either is truthy or both are falsy. It would NOT return the value of $b if $a was falsy:
$a = FALSE;
$b = "I'm b";
echo $a || $b;
// Prints "1", not "I'm b"
So to answer the question, PHP will do a boolean comparison of the two values and return the result. It will not return the first truthy value of the two.
More idiomatically in PHP (if there is such a thing as idiomatic PHP) would be to use a ternary operation:
$c = $a ? $a : $b;
// PHP 5.3 and later supports
$c = $a ?: $b;
echo $a ?: $b;
// "I'm b"
Update for PHP 7
PHP 7 introduces the ?? null coalescing operator which can act as a closer approximation to conjunction. It's especially helpful because it doesn't require you to check isset() on the left operand's array keys.
$a = null;
$b = 123;
$c = $a ?? $b;
// $c is 123;

Related

Is !empty($a) ? $a : $b the same as $a ?: $b in PHP

I'm working on a new project and I've come upon the question if the ternary short hand operator the same as using the traditional ternary in combination with the empty() function?
For clarity purposes my question is if: $a ?: $b is the same as !empty($a) ? $a : $b ?
$a ?: $b is short-hand for $a ? $a : $b which is not quite the same as !empty($a) ? $a : $b
The difference between them requires careful reading of the definition of the empty pseudo-function:
Determine whether a variable is considered to be empty. A variable is considered empty if it does not exist or if its value equals false. empty() does not generate a warning if the variable does not exist.
When you just use $a "in boolean context", as in if ( $a ) or $a ? $a : $b or $a ?: $b, its value will be converted to boolean. If the variable doesn't exist - a mistyped variable name, for instance - a Warning will be issued while retrieving that value.
The special power of the empty() pseudo-function is that it won't give you that Warning. The actual result will be the same - an unset variable is considered "equal to false" - but the two pieces of code aren't always interchangeable.

PHP if execution

In PHP if you have the following code does $b get evaluated since $a will cause the if statement to return false?
$a = false;
$b = true;
if ($a && $b) {
// more code here
}
also if $b does get evaluated are there ever circumstances where a portion of an if statement may not be evaluated as the processor already knows that the value to be false?
Evaluation of && is stopped as soon as it hits the false condition.
These (&&) are short-circuit operators, so they don't go to check second condition if the first one true (in case of OR) or false(in case of AND).
Reference: http://php.net/manual/en/language.operators.logical.php
From documentation:
<?php
// --------------------
// foo() will never get called as those operators are short-circuit
$a = (false && foo());
$b = (true || foo());
$c = (false and foo());
$d = (true or foo());
Evaluation of logical expressions is stopped as soon as the result is known.
If $a is false, $b will not get evaluated, as it won't change the ($a && $b) result.
A consequence of that is that if the evaluation of $b requires more ressources than the evaluation of $a, starts your test condition with $a.
But be aware that:
PHP does not (in the general case) specify in which order an expression is evaluated and code that assumes a specific order of evaluation should be avoided, because the behavior can change between versions of PHP or depending on the surrounding code. (Source php docs)
So you should not assume $b is never evaluated if $a is false, as it may change in the future (says php docs).

PHP or shorthand for empty variable

$a = '';
$b = 1;
How to print $b if $a = '' using shorthand in PHP?
in javascript there is something like
a || b;
Ternary Operator
$a = '';
$b = 1;
echo $a ?: $b; // 1
Until $a is evaluated false, $b will be displayed. Remember that the following things are considered to be empty:
"" (an empty string)
0 (0 as an integer)
0.0 (0 as a float)
"0" (0 as a string)
NULL
FALSE
array() (an empty array)
$var; (a variable declared, but without a value)
That means that if $a is "", 0, "0", null, false, array(), .. then $b will be displayed. See PHP type comparison tables.
If you want to display $b only when $a is an empty string, then you should uses strict comparison operators (===)
$a = '';
$b = 1;
echo $a === '' ? $b : ''; // 1
This is the shorthand for an IF/Else statement in PHP.
echo ($a != '' ? $a : $b)
If $a is not an empty string output (echo) $a otherwise output $b.
As others ahve said Turnary operator is handy for most senarios.
echo $a ?: $b;//b
But it is NOT shorthand for empty().
Ternary operator will issue notices if var/array keys/properties are not set.
echo $someArray['key that doesnt exist'] ?: $b;//Notice: Undefined index
echo $arrayThatDoesntExist['key-that-doesnt-exist'] ?: $b;//Notice: Undefined variable
empty() will take care of the additional checks for you and its recomended to just use it.
if (empty($arrayThatDoesntExist['key-that-doesnt-exist'])) echo $b;
You could technically just suppress the warning/notice with # and the ternary operator becomes a replacement for empty().
#echo $someArray['key that doesnt exist'] ?: $b;
#echo $arrayThatDoesntExist['key-that-doesnt-exist'] ?: $b;
But usually not recommended as supressing notices and warnings could lead you into trouble later on plus I think it may have some performance impact.

Precedence operator 'OR' and '=' in PHP

$a = 1;
$a OR $a = 'somthing'
echo $a; //1
Why? If = have much precedence then 'OR' then why OR execute first?
When you put OR between two statement, if the first one returns true, the second one never will be executed.
in this case, the first statement ( $a ) returns true ( because $a = 1 ), so the
second one ( $a = 'somthing'; ) wont be executed.
Because if OR has higher precedence then
$a OR $a = 'somthing'
will be parsed as:
($a OR $a) = 'somthing'
that would be technically wrong because you can't assign to an expression (while programmers would like to write expression like this is coding so it should be a valid expression).
because precedence of or operator was low hence the expression $a OR $a = 'somthing' pareses as $a OR ($a = 'somthing') And according to short-circuit first operand that is $a was evaluated as true and second operand expression not evaluated and a remains 1.
Remember precedence rules derives grammar rules and hence tells how expression will be parse. But precedence is a compile-time property that tells us how expressions are structured. Evaluation is a run-time behavior that tells us how expressions are computed (hence how expressions will be evaluates can't completely determine by precedence). And PHP docs seems to say same:
Operator Precedence
Operator precedence and associativity only determine how expressions
are grouped, they do not specify an order of evaluation. PHP does not
(in the general case) specify in which order an expression is
evaluated and code that assumes a specific order of evaluation should
be avoided, because the behavior can change between versions of PHP or
depending on the surrounding code.
Because 1 is truthy.
What you're saying with $a OR $a = 'somthing';
is
a is true OR set it to "somthing"
.
Well, a is true, so it won't be set, while the following code would do.
$a = false;
$a OR $a = 'somthing';
echo $a; //"something"

Javascript-like syntax in php [duplicate]

Javascript employs the conjunction and disjunction operators.
The left–operand is returned if it can be evaluated as: false, in the case of conjunction (a && b), or true, in the case of disjunction (a || b); otherwise the right–operand is returned.
Do equivalent operators exist in PHP?
PHP supports short-circuit evaluation, a little different from JavaScript's conjunction. We often see the example (even if it isn't good practice) of using short-circuit evaluation to test the result of a MySQL query in PHP:
// mysql_query() returns false, so the OR condition (die()) is executed.
$result = mysql_query("some faulty query") || die("Error");
Note that short-circuit evaluation works when in PHP when there is an expression to be evaluated on either side of the boolean operator, which would produce a return value. It then executes the right side only if the left side is false. This is different from JavaScript:
Simply doing:
$a || $b
would return a boolean value TRUE or FALSE if either is truthy or both are falsy. It would NOT return the value of $b if $a was falsy:
$a = FALSE;
$b = "I'm b";
echo $a || $b;
// Prints "1", not "I'm b"
So to answer the question, PHP will do a boolean comparison of the two values and return the result. It will not return the first truthy value of the two.
More idiomatically in PHP (if there is such a thing as idiomatic PHP) would be to use a ternary operation:
$c = $a ? $a : $b;
// PHP 5.3 and later supports
$c = $a ?: $b;
echo $a ?: $b;
// "I'm b"
Update for PHP 7
PHP 7 introduces the ?? null coalescing operator which can act as a closer approximation to conjunction. It's especially helpful because it doesn't require you to check isset() on the left operand's array keys.
$a = null;
$b = 123;
$c = $a ?? $b;
// $c is 123;

Categories