This question already has answers here:
Reference Guide: What does this symbol mean in PHP? (PHP Syntax)
(24 answers)
Closed 9 years ago.
if ($form->isValid()) {
// ... perform some action, such as saving the task to the database
$nextAction = $form->get('saveAndAdd')->isClicked()
? 'task_new'
: 'task_success';
return $this->redirect($this->generateUrl($nextAction));
}
Here is the link to the documentation
http://symfony.com/doc/current/book/forms.html
The class documentation says that it returns a bool.
What is the point of
? 'task_new'
: 'task_sucess';
That is called "ternary" and it's awesome:
This is assigning the value $nextAction based on a condition. The first part (after the =) is the condition, like an if statement, the second part (after the ?) is the value assigned if the condition is true, and the last part (after the :) is the value assigned if the condition is false.
//the condition
$nextAction = $form->get('saveAndAdd')->isClicked()
? 'task_new' //true value
: 'task_success'; //false value
It is a shorter way of writing this:
if ($form->get('saveAndAdd')->isClicked()) {
$nextAction = 'task_new';
}
else {
$nextAction = 'task_success';
}
So, here's some easy examples:
$foo = (true) ? 'True value!' : 'False value!';
echo $foo; //'True value!' of course!
$foo = (false) ? 'True value!' : 'False value!';
echo $foo; //'False value!' of course!
It's the Ternary operator. The syntax is as follows:
value = (condition) ? run if true : run if false;
In this case, if $form->get('saveAndAdd')->isClicked() is true, then task_new. Else task_success.
If could be rewritten like so:
if($form->get('saveAndAdd')->isClicked()) {
$value = "task_new";
} else {
$value = "task_success";
}
The ternary operator is a shorter form for an if statement.
The : is the "else" part.
Example in Java:
boolean bool;
true ? bool = true : bool = false;
It's a senseless example, but shows the ternary operator very well.
if the condition, here true is "true", then fill into the variable bool true, else false.
alternative if-statement in Java to the code example above:
boolean bool;
if(true)
bool = true;
else
bool = false;
This is a Ternary Operator which is a short hand if else statement. This is equivalent to
if($form->get('saveAndAdd')->isClicked()){
$nextAction = 'task_new'
else{
$nextAction = 'tassk_success'
}
This is the ternary opeator, a short-hand expression that works the same as an if
$value = someFunc() ? "whatever" : "the other"
is equivalent to
if (someFunc()) {
$value = "whatever";
} else {
$value = "the other";
}
This is equivalent to "if" and "else" statements.
This code :
$nextAction = $form->get('saveAndAdd')->isClicked()
? 'task_new'
: 'task_success';
is equivalent to this code :
if ( $form->get('saveAndAdd')->isClicked() )
{
$nextAction = 'task_new';
}
else
{
$nextAction = 'task_success';
}
Related
I have a conflict regarding else condition. I can write a program in 2 ways.
Method 1
$msg = '';
if(cond)
{
$msg = 'success';
}
else
{
$msg = 'error';
}
Method 2
$msg = 'error';
if(cond)
{
$msg = 'success';
}
Can you please tell me which method is better and how? Thanks
Between the two, I'd choose the first one.
$msg = '';
if(cond) {
$msg = 'success';
} else {
$msg = 'error';
}
This is readable and clearly conveys what it's trying to do.
If the condition is true, the message will be success. If not, the message will be error.
But for something really simple as above, I'd use a ternary statement instead. It's very useful and can cut down code, but may make your code unreadable in some cases:
$msg = (cond) ? "success" : "error";
Pretty cool, right? Read more about ternary operators here.
Use the ternary operator:
$msg = (cond) ? 'success' : 'error';
I'd say the second one is better cause it's less lines and it has a default behavior. No matter what, you know that $msg will contain something, even if you add other checks down the road. However, I would use the Ternary operator in this case:
$msg = (cond) ? 'success' : 'error';
Code readability matters, so I'd use ternary operator when it really simplifies the look.
Consider this,
function foo($stuff) {
$var = null;
if ($stuff === true) {
$var = true;
} else {
$var = false;
}
return $var !== null ? true : false;
}
Since in this case, return $var !== null ? true : false is pretty short, it can be considered as "easy to read and understand".
Consider this,
function foo($stuff) {
$var = null;
if ($stuff === true) {
$var = true;
} else {
$var = false;
}
if ($var !== null) {
return true;
} else {
return false;
}
}
The same thing, but a little bit longer
Conclusion
if a condition isn't that long, it's okay to stick with ternary operators (Because of readability). But if its not, then you'd better stick with if/else
Also you should call this thing "Approach", not a "method", because a method is a function within a class.
I know there is a shorthand for IF/ELSE STATEMENT in PHP such as
($user['permissions'] == 'admin' ? true : false);
But is there a shorthand for ELSE IF statement besides switch?
What you could do
You can keep chaining ternary operators together, e.g.:
$x = $condition1 ? true : ($condition2 ? true : false);
It looks nice now, but once your conditions grow bigger, it quickly becomes unreadable. Note that parentheses are bare essentials for these kind of expressions.
What you should do
Once you add more conditions, prefer to use the proper branching syntax; always assume the person who later has to take over your code is a psychopath who knows where you live:
$canAccess = false;
if ($user['permissions'] == 'admin') {
$canAccess = true;
} elseif ($user['permissions'] == 'whatever') {
$canAccess = true;
}
Yes, you could use an or in the first statement too.
Or, a switch:
switch ($user['permissions']) {
case 'admin':
case 'whatever':
$canAccess = true;
break;
default:
$canAccess = false;
}
I’d rather just use elseif() {} anyway
$somevalue == 'foo' ? 'is foo' : ($somevalue == 'bar' ? 'is bar' : 'is neither');
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
What is the PHP ? : operator called and what does it do?
i was interviewed with a very basic question of PHP which was like:
echo ('True' ? (true ? 't' : 'f') : 'False');
Can Someone explain the details of the output it will yield?
Thanks
This will echo t.
Because of first it will check the first condition that will give true.
and after that in next condition it again give true and execute the first condition that is t.
In if and else condition it will be write as follow:
if('True') { //condition true and go to in this block
if(true){ //condition true and go to in this block
echo 't'; // echo t
} else {
echo 'f';
}
} else {
echo 'False';
}
Looking at this version should make it clear:
if('True'){ // evaluates true
if(true){ // evaluates tre
echo 't'; // is echo'd
}else{
echo 'f';
}
}else {
echo 'False';
}
A non-empty string is considered a truthy value except the string "0". PHP evaluates
'True' ? (true ? 't' : 'f') : 'False'
from left to right as follows:
The expression 'True' is evaluated as a boolean true
Next, the expression following the ? is evaluated
The expression true is... true!
The expression following the ? is returned, which is t
Surprisingly, you'll still get t if the expression was:
echo 'False' ? (true ? 't' : 'f') : 'False'
As 'True' is Evaluated as true
if('True'){
if(true){
echo 't';
}else{
echo 'f';
}
}else{
echo 'False';
}
The inner bracket will be executed first true?'t':'f' it will return 't' that is a string
Now outer condition will check for echo ('True' ? 't' : 'False'). Here 'True' is a "non empty string"(implicitly casted to TRUE), so it evaluate to true, and will return 't'.
Final code will be echo ('t') which will simply echo t
echo ( // will echo the output
'True'? // first ternary operation 'True' is considered true
(true? 't':'f') // will go here for the second ternary operation
// true is also evaluated as true so it will echo 't'
: 'False'); // never goes here
This:
'True'?(true?'t':'f'):'False'
May be written as
// Will always be true if String is not an Empty string.
if('True'){
// if (true) will always enter
if(true){
// t will be the output
echo 't';
}else{
echo 'f';
}
else {
echo 'False';
}
I'd love to know what this means so I can google it as I see it all the time and it seems to be very useful
(($winstate==1)?'X':'O')
edit: The vars are irrelevant.
Thanks guys
That's called a ternary operator, it's PHP's only ternary operator, and it's shorthand for a conditional:
if($winstate == 1){
return 'X';
}else{
return 'O';
}
It's frequently used when the conditional test results in an assignment or returns something, in this case suppose you wanted to assign 'X' or 'O' to a variable $move, it's far more concise to write:
$move = ($winstate == 1) ? 'X' : 'O';
Look at Comparsion Operators
There's everything explained
<?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'];
}
?>
Is there a function to check both
if (isset($var) && $var) ?
The empty() function will do the job.
Use it with the not operator (!) to test "if not empty", i.e.
if(!empty($var)){
}
You may use the ?? operator as such:
if($var ?? false){
...
}
What this does is checks if $var is set and keep it's value. If not, the expression evaluates as the second parameter, in this case false but could be use in other ways like:
// $a is not set
$b = 16;
echo $a ?? 2; // outputs 2
echo $a ?? $b ?? 7; // outputs 16
More info here:
https://lornajane.net/posts/2015/new-in-php-7-null-coalesce-operator
there you go. that should do it.
if (isset($var) && $var)
if (! empty($var))
It seems as though #phihag and #steveo225 are correct.
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.
No warning is generated if the variable does not exist. That means
empty() is essentially the concise equivalent to !isset($var) || $var
== false.
So, it seems !empty($var) would be the equivalent to isset() && $var == true.
http://us2.php.net/empty
Try the empty function:
http://us2.php.net/empty
isset($a{0})
isset AND len is not 0 seems more reliable to me, if you run the following:
<?php
$a=$_REQUEST['a'];
if (isset($a{0})) { // Returns "It's 0!!" when test.php?a=0
//if (!empty($a)) { // Returns "It's empty!!" when test.php?a=0
echo 'It\'s '.$a;
} else { echo 'It\'s empty'; }
?>
$a = new stdClass;
$a->var_false = false;
$a->var_true = true;
if ($a->notSetVar ?? false) {
echo 'not_set';
}
if ($a->var_true ?? false) {
echo 'var_true';
}
if ($a->var_false ?? false) {
echo 'var_false';
}
This way:
if (($var ?? false) == true) {
}
I am amazed at all these answers. The correct answer is simply 'no, there is no single function for this'.
empty() tests for unset or false. So when you use !empty(), you test for NOT UNSET (set) and NOT FALSE. However, 'not false' is not the same as true. For example, the string 'carrots' is not false:
$var = 'carrots'; if (!empty($var)){print 1;} //prints 1
in fact your current solution also has this type problem
$var = 'carrots'; if (isset($var) && $var){print 1;} //prints 1
as does even this
$var = '1.03'; if (isset($var) && $var == true){print 1;} //prints 1
in fact... if you want to do as you described exactly, you need:
$var = 'carrots'; if (isset($var) && $var === true){print 1;} //Note the 3 Equals //doesn't print 1
I suppose the shortest valid way to test this case is :
if (#$var === true){ print 1;}
But suppressing errors for something like this is pretty awful practice.
Don't know if an exact one already exists, but you could easily write a custom function to handle this.
function isset_and_true($var) {
return (isset($var) && $var == true) ? true : false;
}
if (isset_and_true($a)) {
print "It's set!";
}
Check if the variable is set, and true. Ignore warning message
if(#!empty($foo))