This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Reference - What does this symbol mean in PHP?
I've been doing conditionals with if/else or a year or so now. Looking at some new code, I'm seeing a conditional that appears to use ? and : instead of if and else. I'd like to learn more about this, but I am not sure what to google to find articles explaining how it works. How can I do it?
It's the Ternary Operator.
Basic usage is something like
$foo = (if this expressions returns true) ? (assign this value to $foo) : (otherwise, assign this value to $foo)
It can be used for more than assignment though, it looks like other examples are cropping up below.
I think the reason you see this in a lot of modern, OO style PHP is that without static typing you end up needing to be paranoid about the types in any particular variable, and a one line ternary is less cluttered than a 7 line if/else conditional.
Also, in deference to the comments and truth in naming, read all about the ternary operators in computer science.
That would be the conditional operator. It's pretty much a single line if/then/else statement:
if(someCondition){
$x = doSomething();
}
else{
$x = doSomethingElse();
}
Becomes:
$x = someCondition ? doSomething() : doSomethingElse();
It is:
condition ? do_if_true : do_if_false
So, for example in the below, do->something() will be run.
$true = 1;
$false = 0
$true ? $do->something() : $do->nothing();
But in the below example, do->nothing() will be run.
$false ? $do->something() : $do->nothing();
This is the ternary operator in PHP. It's shorthand for if/else, format is:
condition ? true expression : false expression;
Related
This question already has answers here:
Short-circuit evaluation via the AND operator in PHP
(5 answers)
Closed 6 years ago.
This is just more of a "why does it work" and "why or why not use it" type question.
We all know PHP expressions using ternary operations
$var = (isset($i) ? true:false);
But in PHP something like the following works too. (It is not ternary, 3 parts, it is more of a binary operation, 2parts.)
$var = true;
isset($i) || $var = false;
Which may not be so practical :) but a more useful construction is
isset($i) || exit();
So the above (much better looking imo) would have the same result as
if(!isset($i)) exit();
But other than the common
defined('CONSTANT') || define('CONSTANT','FOO');
I rarely see this type of construct used in PHP. Why does this work? What is it called. Why is it not taught or used more. Are there cons to using it? And is there practical ways to use && in the same way?
This way of writing statements also exists in C, Perl and other languages, it plays with how the compiler evaluates statements chained with logical operators.
Imagine you have an expression if (a() or b()), then when a() returns true you don't have to evaluate b(), because the entire statement is true already. So b() is only called when a() is false. You can write this without the if, it still works the same way.
This shorthand is usually found like you described, to define default values or exit if a condition is not met.
This question already has answers here:
What's the meaning of the reverse entry (null === $value) when checking the value of the variable? [duplicate]
(4 answers)
Closed 6 years ago.
Often, I see in if statements for php something like this:
if (null === $variable) {
// do stuff
}
What does it do and what is it for?
EDIT: I totally get that it is a comparison operator, I just wonder why not $variable === null.
It's not an assignment, it's a comparison for equality. It determines if the variable $variable contains the value null.
More in the documentation:
Assignment Operators
Comparison Operators
why not to check $variable === null
Some people like to use the form with the constant on the left (a "Yoda condition", it is called) so that if they have a typo and only type a single =, it causes a syntax error rather than doing an assignment.
That is the Yoda style usually used as a trick by programmers to prevent accidental assignments which always give some silent bugs.
Example:
var a = dosomething();
if(a = null){
//more here
}
Note that the if block will always not execute regardless of the result of doSomething method since we assign then check for equality. This assignment nullifies the possibly non-deterministic nature of doSomething
This question already has answers here:
'AND' vs '&&' as operator
(10 answers)
Closed 7 years ago.
Why is $x true in this statment?
$x = true and false;
I've got the problem with some variables but I could reduce the problem to the primitive boolean values.
Update:
As you see in the replies the effect has to do with the operator precedense in PHP. There is also a good explanation about the problem in this question, which I couldn't find in the net before since I didn't know that I have a problem with this and I didn't know that there is a difference between '&&'/'||' and 'and'/'or'.
After some search I found out that this is caused by the operator precedence in PHP. The '=' operator is stronger than 'and'.
If you want to get the expected result you have to use braces:
$x = (true and false); //correct: $x is false now!
Without braces the expression is equal to ($x = true) and false; . $x will get the 'true' value. After that the PHP interpreter 'replaces' this assignment with the value that $x has just got. So true and false; remains. And that does not do anything. 'false' is lost and didn't influence the expression.
Be aware that the braces are NOT required if you use '&&' or '||'! They are stronger than '=' and thus stronger than 'and' and 'or'. Strange...
This is different to e.g. $x = 5 + 6; since here '+' is stronger than '=' it will be resolved first. In the end it affects only the boolean operators 'and', 'or' and 'xor'. Only with them you have to watch out.
Note also that this is different compared to other languages like JavaScript or Java. In those languages you don't need the braces since the logical operators are stronger than the equal operator (Operators in JavaScript, Operators in Java).
More on this:
$x = true and false;
So we have the following. If you guessed that $x is true, you'd be right. Since = has a higher precedent than and.
Rewriting the expression above it would be equal to this:
($x = true) and false;
Here's where it gets funny.
If you were to do:
$x = true && false;
and you'd guess that $x is true, you'd be wrong. $x is actually false in this case.
The above expression is actually equal to:
$x = (true and false);
Why? Because && has a higher precedent than and.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Where can I read about conditionals done with ? and :
I want do the following without using if else or a ternary operator:
if $_GET['a'] is not null then set $a= $_GET['a'] else set its value to "default".
I tried $a= $_GET['a'] || "default". but it doesnt work.
I remember seeing something like this in a code sample, but I can't recall now.
I think a ternary if is your best bet here.
In this case I would use isset check - to determine if the key is set and is not null:
$a = isset($_GET['a']) ? $_GET['a'] : "default"
The or operator || doesn't work to null coalesce like that in PHP, but you might have seen it in JavaScript where it can be used to set a value to the first non-false result:
e.g
var a = get['a'] || 'default';
Refer this PHP shorthand if/else (ternary) information in http://davidwalsh.name/php-ternary-examples
and also
http://davidwalsh.name/learning-ternary-operators-tips-tricks
Well, people here doesn't seem to bother reading the entire question this late.
That sintax you wrote works on some other languages but apparently not on php. I think you should just stick to the ternary operator or write a function for that as a shortcut if you're going to use this kind of verification a lot on your page.
function GET($v, $default)
{
return !isset($_GET[$v]) || empty($_GET[$v]) ? $default : $_GET[$v];
}
$a = GET("a", "default");
This question already has answers here:
Setting default values (conditional assignment)
(6 answers)
Closed 4 years ago.
what's the PHP equivalent of Ruby's "||=" assignment idiom?
The scenario is I want to instantiate an object or array "on demand," and not necessarily when a class is initialized.
I've tried to find this in the PHP docs, but I'm having difficulty finding things I need in there (miss the Ruby).
Thank you!
I don't think PHP has a similar assignment syntax. You'll have to fake it with something like this:
if (empty($someVar)) $someVar = "DefaultVal";
Note: I'm not familiar with Ruby, so I read up on the ||= operator here. I'm not sure how that operator, as explained at that link, would help you do what you want either, but whatever.
What about:
<?php $someVar ?: 'default value'; ?>
This works well with PHP 5.3.
The answer is right but if the value does not exist it will raise an E_NOTICE. For example for $_GET['key']. If key is not in the array of $_GET it will raise an E_NOTICE.
If you are working with PHP 7 (which I totally recommend to use) there's a new feature called Null Coalesce Operator.
This way it returns the result of its first operand if it exists and is not NULL, or else its second operand:
<?php $foo = $foo ?? 'default value'; ?>
This is one of those things I miss from Ruby. You can also do:
$foo = empty($foo) ? "default" : $foo;
Ugly as hell though.