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');
Related
I'm trying to shorthand the following if else statement. But getting errors.
if ($jobs->due_out == null) {
return ('N/A');
} else {
return date(self::DATETIME, strtotime($jobs->due_out));
}
This is what i tried so far:
return 'N/A' ? $jobs->due_out == null : date(self::DATETIME, strtotime($jobs->due_out);
This is in Php. Any suggestions ?
Your statement is slightly the wrong way round, you need the condition first...
return ($jobs->due_out == null) ? 'N/A' : date(self::DATETIME, strtotime($jobs->due_out));
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';
}
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'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 it possible to use three parameters in switch-case, like this:
switch($var1, $var2, $var3){
case true, false, false:
echo "Hello";
break;
}
If not, should I just use if-else or is there a better solution?
The syntax is not correct and I wouldn't recommend it, even if it was. But if you really want to use a construct like that, you can put your values into an array:
switch (array($var1, $var2, $var3)) {
case array(true, false, false):
echo "hello";
break;
}
I would just use the if/else
if($var1 == true && $var2 == false && $var3 == false){
echo "Hello";
}
or
if($var1 && !($var2 && $var3)) {
echo "Hello";
}
You don't have a switch situation here. You have a multiple condition:
if($var && !($var2 || $var3)) { ...
i don't think your syntax is valid.
I'd nest the switch statements.
Another option is to create a function that maps three parameters to an integer and use that in the switch statement.
function MapBool($var1, $var2, $var3){
// ...
}
switch(MapBool($var1, $var2, $var3)) {
case 0:
echo "Hello";
break;
// ...
}
This is the sort of thing that used to be handled by bitwise operators:
if (($var1 << 2) & ($var2 << 1) & $var3) == 4) ...
...back when 'true' was 1.
That being said, the above is concise, but it's pretty hard to read and maintain. Nevertheless, if you have a lot of similar statements, shifting/ANDing might be a way to go to get things under control:
switch (($var1 << 2) & ($var2 << 1) & $var3)) {
case 0: // false, false, false
...stuff...
case 1: // false, false, true
...different stuff...
// all 8 cases if you REALLY care
}
I don't know - if you really want it this way - maybe cast them all to string, concatenate and then use the resulting string in your case condition?