php: operator precedence - php

I found this question at http://www.phpinterviewquestions.com/php-interview-questions/operator-precedence/
Following operations are true or false? (Operator Precedence)
$one = true;
$two = null;
$a = isset($one) && isset($two);
$b = isset($one) and isset($two);
echo $a.'<br>';
echo $b;
I tried the above code. But only $b gets echoed as 1 (which is true). $a is not getting echoed. What could be the reason? I was expecting $a to be 0 (false).

It's not about precedence, it's about implicit type casting
Use var_dump($a); instead of echo $a;
$a actually is false, but being echo'ed false is casted to empty string.

Related

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.

PHP multiplication

It is my first question, so hi all..
Is it possible to satisfy this condition?
Where $a and $b are some defined variables
if(!is_numeric($a * $b.'')) { ... }
EDIT: Second conditon
$a * $b can't be INF
You can satisfy the condition with specific values of $a and $b. For example, $a = $b = 1e200, or $a = 1e400, $b = 0.
If the product of $a and $b overflows to infinity or is a not-a-number, the concatenation with an empty string will produce the string INF or NAN:
php > var_export(1e200*1e200);
INF
php > var_export(is_numeric(1e200*1e200));
true
php > var_export(is_numeric(1e200*1e200.''));
false
php > var_export(1e400*0);
NAN
php > var_export(is_numeric(1e400*0));
true
php > var_export(is_numeric(1e400*0 .''));
false
Tested using 32-bit PHP
$a = 9.9E300;
$b = 9.9E300;
if(!is_numeric($a * $b.'')) {
echo 'non-numeric';
} else {
echo 'numeric';
}

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;

Does PHP support conjunction and disjunction natively?

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;

Operator precedence issue in Perl and PHP

PHP:
$a = 2;
$b = 3;
if($b=1 && $a=5)
{
$a++;
$b++;
}
echo $a.'-'.$b;
$a = 2;
$b = 3;
if($a=5 and $b=1)
{
$a++;
$b++;
}
echo $a.'-'.$b;
Output 6-16-2.I don't understand the 1 here.
Perl :
$a = 2;
$b = 3;
if($b=1 && $a=5)
{
$a++;
$b++;
}
print $a.'-'.$b;
$a = 2;
$b = 3;
if($a=5 and $b=1)
{
$a++;
$b++;
}
print $a.'-'.$b;
Output 6-66-2, I don't understand the second 6 here.
Anyone knows the reason?
Actually I know && has higher precedence than and,but I still has the doubt when knowing this before hand.
UPDATE
Now I understand the PHP one,what about the Perl one?
Regarding Perl:
Unlike PHP (but like Python, JavaScript, etc.) the boolean operators don't return a boolean value but the value that made the expression true (or the last value) determines the final result of the expression† (source).
$b=1 && $a=5
is evaluated as
$b = (1 && $a=5) // same as in PHP
which is the same as $b = (1 && 5) (assignment "returns" the assigned value) and assigns 5 to $b.
The bottom line is: The operator precedence is the same in Perl and PHP (at least in this case), but they differ in what value is returned by the boolean operators.
FWIW, PHP's operator precedence can be found here.
What's more interesting (at least this was new to me) is that PHP does not perform type conversion for the increment/decrement operators.
So if $b is true, then $b++ leaves the value as true, while e.g. $b += 1 assigns 2 to $b.
†: What I mean with this is that it returns the first (leftmost) value which
evaluates to false in case of &&
evaluates to true in case of ||
or the last value of the expression.
First example
$a = 2;
$b = 3;
if($b=1 && $a=5) // means $b = (1 && $a=5)
{
var_dump($b); //bool(true) because of &&
$a++;
$b++; //bool(true)++ ==true, ok
}
echo $a.'-'.$b;
hope you will not use those codes in production)
I'm noob in perl but i can suggest a&&b returns a or b (last of them if all of them converted to bool), not boolean, then $b = (1 && $a=5) returns $b=5 (is 5)
here's the issue: 1 && 5 returns 5 in perl. you get the result you expect if you code the conditional as if(($b=1) && ($a=5))
For Perl, fig. 2: and has a very low priority in perl, it's not a synonym of &&'s. Therefore the sample is executed as (($a = 5) and ($b = 1)) which sets $a and $b to 5 and 1 respectively and returns a value of the last argument (i.e. 1).
After ++'s you get 6-2.
refer to http://sillythingsthatmatter.in/PHP/operators.php for good examples

Categories