Else statement usage - php

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.

Related

I am not understanding why this is happening with empty php variables

I try to do this:
if ($var !== ""){
$message = "whatever";
}
But end up having to do this:
if ($var == ""){
//do nothing
} else {
$message = "whatever";
}
Why does that happen? Shouldn't both of those mean the same thing?
!= and == are opposites (non-strict comparison operators).
!== and === are opposites (strict comparison operators, where the value must match what you are comparing exactly).
If you use != instead of !==, your code should work. But:
You should understand what the actual value of your variable is - it's not an empty string. You can use print_r( $var ); to see it.
It's better to use the strict comparison operators === and !==, because they have well-defined behavior that is easier to remember and debug.
As $var is really string just use:
if ($var){//any non-empty string will work fine as it will be casted to boolean automatically
$message = "whatever";
}
$var could be != '' but not= '' eg .. null
if ($var == ""){
//do nothing
} else {
if (is_null($var) {
$message ='NULL';
} else {
$message = "whatever";
}
}

PHP ternary operators

I have written a ternary function in PHP and it seems to work, although I am not sure if it is correct, can someone take a look and tell me if it is right?
I have added the ternary and the if of what should be happening.
//Foreach Loop
foreach ($post as $item) {
//If of what should occur
if ($passed == true) {
if (is_numeric($item)) {
if ($item > 0) {
$passed = true;
}
else {
$passed = false;
}
}
else {
if ($item != "") {
$passed = true;
}
else {
$passed = false;
}
}
//Ternary operator.
$passed = (is_numeric($item) ? ($item > 0 ? true : false) : ($item != "" ? true : false));
}
else {
return $passed;
}
}
please have a look on corrected code
$passed = (is_numeric($item))?($item>0?true:false):($item !="" ? true:false);
Honestly I do not really understand why you do not use a
if (!empty($item)) {
$passed = true;
} else {
return false;
}
In any case, ternaries are less readable than if /elseif / else, they are also slower (note that it is not an universal truth but a more general use case thing http://fabien.potencier.org/the-php-ternary-operator-fast-or-not.html).
I would recommend, if you really need all these if and elses to keep them rather than using ternaries (for readability's purpose).

What does ':' and '?' mean in the isClicked() symfony [duplicate]

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';
}

Shorthand for else if statment in PHP

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');

Ternary operation returning "Undefined Property"

I have switched from using this ternary operation to if/elseif/else, but I would really like to know why this doesn't work. I keep getting the error:
ErrorException [ Notice ]: Undefined property: stdClass::$error
If I were to switch the order of the conditions so that the $res->response piece was 3rd, then I get the same error but for that property instead. It makes no sense to me, and testing it on Codepad.org (which uses PHP 5.2) it works as expected: http://codepad.org/gwteijIe
Here's the test code in question:
$output = '{"error":{"message":"This is a test error"}}';
$res = json_decode($output);
$error = isset($res->response) ? $res->response->message :
isset($res->error) ? $res->error :
isset($res->error->message) ? $res->error->message :
$output;
echo $error;
(The reason why it checks for $res->error and $res->error->message is because the API we're using will return any one of the three conditions we're checking for. Disclaimer: it's not my API!)
Any insight as to why I am not getting the results I expect? Many thanks in advance for the help.
Edit:
To clarify, this is what I am trying to achieve:
if (isset($res->response))
{
$error = $res->response->message;
}
elseif (isset($res->error->message))
{
$error = $res->error->message;
}
elseif (isset($res->error))
{
$error = $res->error;
}
Don't nest ternary operator.
You see the error because of the order in which ternary operators are evaluated; it would be far better and more maintainable to just write it out like this:
if (isset($res->response)) {
$error = $res->response->message;
} elseif (isset($res->error)) {
if (isset($res->error->message)) {
$error = $res->error->message;
} else {
$error = $res->error;
}
} else {
$error = $output;
}
Your old code evaluates like this; even then it's non-obvious what really happens:
((isset($res->response) ? $res->response->message :
isset($res->error)) ? $res->error :
isset($res->error->message)) ? $res->error->message :
$output;
See also: Comparison Operators

Categories