What does "isset($x) ? $y : $z" mean? [duplicate] - php

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
What are the PHP operators "?" and ":" called and what do they do?
Reference - What does this symbol mean in PHP?
I know what isset means in PHP. But I have seen syntax like isset($x) ? $y : $z. What does it mean?

That is a Ternary Operator, also called the "conditional expression operator" (thanks Oli Charlesworth). Your code reads like:
if $x is set, use $y, if not use $z

In PHP, and many other languages, you can assign a value based on a condition in a 1 line statement.
$variable = expression ? "the expression was true" : "the expression was false".
This is equivalent to
if(expression){
$variable="the expression is true";
}else{
$variable="the expression is false";
}
You can also nest these
$x = (expression1) ?
(expression2) ? "expression 1 and expression 2 are true" : "expression 1 is true but expression 2 is not" :
(expression2) ? "expression 2 is true, but expression 1 is not" : "both expression 1 and expression 2 are false.";

That statement won't do anything as written.
On the other hand something like
$w = isset($x) ? $y : $z;
is more meaningful. If $x satisfies isset(), $w is assigned $y's value. Otherwise, $w is assigned $z's value.

It's shorthand for a single expression if/else block.
$v = isset($x) ? $y : $z;
// equivalent to
if (isset($x)) {
$v = $y;
} else {
$v = $z;
}

It means if $x variable is not set , then value of $y is assigned to $x , else value of $z is assigned to $x.

Related

Nested shorthand if bug [duplicate]

Why is this printing 2?
echo true ? 1 : true ? 2 : 3;
With my understanding, it should print 1.
Why is it not working as expected?
Because what you've written is the same as:
echo (true ? 1 : true) ? 2 : 3;
and as you know 1 is evaluated to true.
What you expect is:
echo (true) ? 1 : (true ? 2 : 3);
So always use braces to avoid such confusions.
As was already written, ternary expressions are left associative in PHP. This means that at first will be executed the first one from the left, then the second and so on.
Separate second ternary clause with parentheses.
echo true ? 1 : (true ? 2 : 3);
Use parentheses when in doubt.
The ternary operator in PHP is left-associative in contrast to other languages and does not work as expected.
from the docs
Example #3 Non-obvious Ternary Behaviour
<?php
// on first glance, the following appears to output 'true'
echo (true?'true':false?'t':'f');
// however, the actual output of the above is 't'
// this is because ternary expressions are evaluated from left to right
// the following is a more obvious version of the same code as above
echo ((true ? 'true' : false) ? 't' : 'f');
// here, you can see that the first expression is evaluated to 'true', which
// in turn evaluates to (bool)true, thus returning the true branch of the
// second ternary expression.
?>
In your case, you should consider the priority of executing statements.
Use following code:
echo true ? 1 : (true ? 2 : 3);
For example,
$a = 2;
$b = 1;
$c = 0;
$result1 = $a ** $b * $c;
// is not equal
$result2 = $a ** ($b * $c);
Are you have used parentheses in expressions in mathematics? - Then, that the result, depending on the execution priority, is not the same. In your case, ternary operators are written without priorities. Let the interpreter understand in what order to perform operations using parentheses.
Late, but a nice example for being carefull from now:
$x = 99;
print ($x === 1) ? 1
: ($x === 2) ? 2
: ($x === 3) ? 3
: ($x === 4) ? 4
: ($x === 5) ? 5
: ($x === 99) ? 'found'
: ($x === 6) ? 6
: 'not found';
// prints out: 6
Result of PHP 7.3.1 (Windows Commandline). I can not understand, why they changed it, because the code becomes really unreadable, if I try to change this.

logical vs assignment operator precedence in PHP

Recently i came upon such snippet:
$x = 2 && $y = 3; echo (int)$x.':'.(int)$y;
Which produces output 1:3.
By looking at operator precedence sheet i see that logical operators || and && has higher precedence than assignment operator =. So first expression should be evaluated as $x = (2 && $y) = 3; which becomes $x = (2 && null) = 3; and finally evaluates to $x = false = 3; Secondly - assignment operator has right associativity, so interpreter should try to execute false = 3 which is illegal of course. So in my opinion above mentioned code snippet should not compile at all and must throw parse or run-time error. But instead of that script produces 1:3. Which means that interpreter executed actions are:
a) $y=3
b) 2 && $y
c) $x = (2 && $y)
Why it is so and not according to operator precedence ?
The operator precedence sheet you link to states as a separate note:
Although = has a lower precedence than most other operators, PHP will
still allow expressions similar to the following: if (!$a = foo()), in
which case the return value of foo() is put into $a.
So, in effect, an assignment inside an expression will be treated somewhat like a sub-expression. Exactly how and when this will happen isn't clear from the documentation, which just states that "similar" expressions will work this way.

PHP - correct ternary implementation [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
Ok,
so consider the following:
$this->foo = isset($_GET['foo']) && !empty($_GET['foo']) ? $_GET['foo'] : NULL;
and this:
$this->foo = (isset($_GET['foo']) && !empty($_GET['foo'])) ? $_GET['foo'] : NULL;
When I write an if / else statement with multiple checks, I generally include the extra parenthesis as in the second example. In the ternary, both examples work.
Should I add the extra parenthesis as on the bottom? Or go with the first?
Thanks
Operator precedence is the issue as to when parenthesis are necessary (notwithstanding readability).
When dealing with the ternary operator look at the order PHP uses to group expressions, start with the ternary operator(s) and examine the operators that are grouped after the ternary operator. Those are the operators that have the potential to produce erroneous output.
PHP Operator Precedence, starting with ternary:
Assoc. Operators Additional Information
...
left ? : ternary
right = += -= *= **= /= .= %=
&= %= &= |= ^= <<= >>= => assignment
left and logical
left xor logical
left or logical
left , many uses
In this case there are the assignment operators, the lower precedence logical operators, and comma.
It appears the ternary and assignment are equal, therefore grouping is determined by their associativity when the two are in the same statement.
$a = true? 'yes': 'no';
// $a is assigned 'yes'
Assignment is right associative so, in relation to the =, expressions are grouped right to left. In this case the ternary comes first (rightmost) and the statement works as expected.
That leaves the lower precedence boolean and the comma.
echo true and true? 'yes': 'no';
// Echos: 1
// Grouped like: echo true and (true? 'yes': 'no');
Not as expected. Use parenthesis to force intended grouping:
echo (true and true)? 'yes': 'no';
// Echos: yes
When using higher precedence boolean operators, which are grouped before the ternary operator, parenthesis are not necessary.
echo true && true? 'yes': 'no';
// Echos: yes
Bottom line, when operator precedence is unclear, or readability is desired, use parenthesis.
The PSR-2 standard specifically omits any opinion on operators. But in this case, i'll go with the simple one:
$this->foo = isset($_GET['foo']) && !empty($_GET['foo']) ? $_GET['foo'] : NULL;
I am for the first approach:
$this->foo = isset($_GET['foo']) && !empty($_GET['foo']) ? $_GET['foo'] : NULL;
simplified to
$this->foo = !empty($_GET['foo']) ? $_GET['foo'] : NULL;
empty already check the isset. I would include parathenis in this case only when condition has more then 3 statements. Consider that the 1 line if/else normally is used when the condition is simple, other wise to have a more readable if else you should go with classic if {} else {}

php "?" operator - ($some_var) ? func() : func(); [duplicate]

This question already has answers here:
Closed 10 years ago.
($some_var) ? true_func() : false_func();
What is this in php, and what does this do? existence, boolean, or what?
It's the same thing as this:
if ($some_var) {
true_func();
}
else {
false_func();
}
If $some_val is true, it executes the function before the :.
If $some_val is false, it executes the function after the :.
It's called the ternary operator.
Typically it's used as an expression when assigning a value to a variable:
$some_var = ($some_bool) ? $true_value : $false_value;
It's one of the most abused programming constructs (in my opnion).
Taken from the PHP Manual: Comparison Operators
<?php
// Example usage for: Ternary Operator
$action = (empty($_POST['action'])) ? 'default' : $_POST['action'];
// The above is identical to this if/else statement
if (empty($_POST['action'])) {
$action = 'default';
} else {
$action = $_POST['action'];
}
?>
It's the ternary operator.
Instead of writing
if ($a < $b) {
$minVal = $a;
} else {
$minVal = $b;
}
You can write is as
$minVal = ($a < $b) ? $a : $b;
It's actually a ternary operator. (I mean the operator ?: is a ternary operator).
($some_var) ? func1() : func2();
'$some_var' is a boolean expression.
If it evaluates to true 'func1()' is executed
else 'func2()' is executed.
Well, the way it's written, it does the same as just
func();
(If $somevar is true, invoke func; otherwise, invoke func too!)
it checks for boolean:
When converting to boolean, the following values are considered FALSE:
the boolean FALSE itself
the integer 0 (zero)
the float 0.0 (zero)
the empty string, and the string "0"
an array with zero elements
an object with zero member variables (PHP 4 only)
the special type NULL (including unset variables)
SimpleXML objects created from empty tags
Every other value is considered TRUE (including any resource).
Also have a look at: PHP type comparison tables

In PHP can you use || (or) in the same way as javascript?

Can I use the OR argument in this way in PHP? Meaning if $x is null assign $y to $var.
$var = $x || $y
Simple question, cheers!
No. PHP's boolean operators evaluate to true or false, not the value of the operands as in Javascript. So you'll have to write something like this:
$var = $x ? $x : $y;
Since 5.3, you can write this though, which basically has the same effect as Javascript's ||:
$var = $x ?: $y;
That requires that $x exists though, otherwise you should check with isset first.
No, in this way you assign a boolean to $var
$var = $x or $y;
means: $var is true, if $x or $y. You are looking for the ternary operator
$var = isset($x) ? $x : $y;
// or
$var = empty($x) ? $y : $x;
The ternary operator always works like
$var = $expressionToTest
? $valueIfExpressionTrue
: $valueIfExpressionFalse
With PHP5.3 or later you can omit $valueIfExpressionTrue
$var = $expressionToTest ?: $valueIfExpressionFalse;
$x=0;
$y=9;
$var = ($x)?$x:$y;
echo $var;
if variable x is null then var will be 9,or else it will be value of x.
This question is already answered, but I juist wanted to point your attention to the other usage of OR and AND operators in PHP
defined('SOMETHING') OR define('SOMETHING', 1);
if this case if SOMETHING is not defined (defined('SOMETHONG') evaluates to false) expression after OR will be evaluated
$admin AND show_admin_controls();
if $admin is evaluated to boolean true, show_admin_controls() function will be called
I usually use it to check if some constant is defined, but I've seen a lot of examples of good-looking and really well-readable code using this constructions for other purposes.

Categories