I found that there are many if-else statements, especially nested if else statements, these statements make my code less readable. How to reduce the number of if else statements in PHP?
My tips are as follows:
1.Use a switch statement when it is suitable;
2.use exit() statement when it is feasible;
3. Use ternary statement when it is feasible;
Are there other tips that can reduce if else statements, especially nested if-else statements?
Try to use "early return" when possible in order to reduce nesting depth. Try to use boolean expression evaluation.
Example:
function foo($param)
{
$ret = false;
if(userIsLoggedIn()) {
if(is_array($param)) {
if($param['count'] > 0) {
$ret = true;
}
else {
$ret = false;
}
}
}
return $ret;
}
You could rewrite this like:
function foo($param)
{
if(!userIsLoggedIn()) return false;
if(!is_array($param)) return false;
return $param['count'] > 0;
}
Refactor your code into smaller work units. Too much conditional logic is a code-smell and usually indicates that your function needs to be refactored.
There is an official academic method to refactor and simplify a lot of if conditions, called Karnaugh mapping.
It takes in multiple test conditions and attempts to assist in creating simplified if statements that cover all the required cases.
You can learn more about it from wiki here.
Use the ternary operator, refactor your code, write a function or a class which does all the necessary if else statements.
I work on a lot of code thats full of ever evolving business logic and needs to be modified every other day. Two tips that's certainly helped me keep up with the modifications are: avoid all else statements and return/exit as soon as possible. Never get into deep nesting -> create sub routines/functions.
Replacing all else statements with negated if statements makes your code much easier to read top to bottom (the proximity of the condtion and the code block):
# business logic block
if ( $condition ) {
# do something
# code code code
} else {
# code code code
return;
}
# refactored:
if ( ! $contition ) {
# code code code
return;
}
if ( $condition ) {
# code code code
}
Secondly, return/exit as soon as possible. My opinion of course, but I don't see the point in running through any extra conditions/tests when once you've already determined the result of the subroutine, especially when you would like to read the code top to bottom. Removing all ambiguity makes things simpler.
To conclude, I like to avoid using else especially in long lists of BL. Return as soon as you know the result. If the nesting level is more than 2, create sub routines/functions.
polymorphism could get rid of a few as well, allthough harder to implement to reduce if/else in PHP as it is not type safe...
You can reduce the number of if/else codes by using ternary operator or null coalescing operator like this:
Using the ternary operator:
Variable = (Condition) ? (Statement1) : (Statement2);
$age = 20;
print ($age >= 18) ? "Adult" : "Not Adult";
Output:
Adult
By using the null coalescing operator:
// fetch the value of $_GET['user'] and returns 'not passed'
// if username is not passed
$username = $_GET['username'] ?? 'not passed';
print($username);
print("<br/>");
// Equivalent code using ternary operator
$username = isset($_GET['username']) ? $_GET['username'] : 'not passed';
print($username);
print("<br/>");
// Chaining ?? operation
$username = $_GET['username'] ?? $_POST['username'] ?? 'not passed';
print($username);
Output:
not passed
not passed
not passed
Related
There are few nice ways to write shorthands in PHP.
Less common but shortest example:
!isset( $search_order ) && $search_order = 'ASC';
More common but a little longer:
!isset( $search_order ) ? $search_order = 'ASC' : $search_order = NULL;
We can even combine examples above in to an amazing shorthand:
!isset( $_POST['unique_id'] ) && preg_match( '/^[a-zA-Z0-9]{8}$/', $_POST['unique_id'] ) ? $post_unique_id = $_POST['unique_id'] : $post_unique_id = NULL;
But how do we use examples above with functions and return, example:
function filter_gender_request($data) {
preg_match('/(fe)?male/i', $data, $data);
isset($data[0]) && return $data[0]; // It doesn't work here with return
}
At the same time, if I state the following, instead of isset($data[0]) && return $data[0]; then everything works as expected:
if (isset($data[0]) ) {
return $data[0];
}
What am I doing wrong here? If the very first and shortest example works outside of function flawlessly, why then it doesn't work with return?
Is there a possibility to use shorthands with return?
With your current syntax, what do you expect your function to return when $data[0] is not set? Surely you don't expect your function to not return anything, depending upon a condition.
The only alternative I see is the ternary operator, where you return something other than $data[0] when it is not set:
return isset($data[0]) ? $data[0] : null;
For future googlers.
Use php 7 null coalesce (??) operator
return $data[0] ?? null;
Your amazing shortcut is actually rather hideous code. You are abusing the ternary operator, and that code is actually far LESS readable AND less maintainable than if you'd written it out. People expect ternaries to perform a test and return an either/or value. Performing assignment within it is NOT normal behavior.
The problem with your code is you are trying to execute a return statement as part of the ternary expression. The ternary operator generally results in an assignment as in:
$message = is_error() ? get_error() : 'No Errors';
This results in an assignment to $message based on the return value of is_error(). Your code is trying to process a program control statement within the operation. return cannot be assigned to the variable.
For this reason, what the other users have posted are better options for your situation.
oke I don't know what you are doing but this should work:
return ( isset($data[0]) ? $data[0] : false);
Agreeing with what has been answered here, that shorthand is harder to read once you've gone away from it and come back, or worse, another developer in the future.
Imagine yourself with even a small 500 line script file, with 40 lines of shorthand elseif as you use it, would you be ok trying to add or change code?
Especially when the subject or content is not something you're familiar with, it becomes a headache to debug or make additions.
This is much more manageable and doesn't matter what it's about, it's just code:
if ($var == 'unicorns')
{
$this->remove_horn;
}
elseif ($var == 'horse')
{
$this->glue_on_horn;
}
else
{
$this->must_be_a_zebra;
}
just saying
I've read through a lot of code where they have if statements, i've noticed other languages use this to. Asp being one.
Tried googling but couldn't find a answer for it.
What exactly does ?: stand for and when to use it.
As far as I'm aware ? is equal to if() and : being equal to }else{.
It is the ternary operator (although in most languages it is better-named as the "conditional operator").
People will often erroneously refer to it as "shorthand if/else". But this is a misnomer; if/else is a statement, ?: is an expression. In most languages, these are distinct concepts, with different semantics.
This is called ternary operator.
It is meant to simplify code in some cases. Consider this:
var str;
if(some_condition)
str = 'yes';
else
str = 'no';
This can be easily rewritten as
var str = some_condition ? 'yes' : 'no';
Your assumption is right.
It is a Ternary operation (Wikipedia)
Essentially, the syntax is condition ? then-expession : else-expression. Typically it is used in assigning variables:
varname = something == 123 ? "yes" : "no";
But it can be used pretty much anywhere in place of a value. It's mostly useful for avoiding repetitive code:
if( something == 123) {
varname = "yes";
}
else {
varname = "no";
}
You could read the documentation. The section you're looking for is titled "Ternary Operator".
You can express calculations that might otherwise require an if-else construction more concisely by using the conditional operator. For example, the following code uses first an if statement and then a conditional operator to check for a possible division-by-zero error before calculating the sin function.
if(x != 0.0) s = Math.Sin(x)/x; else s = 1.0;
s = x != 0.0 ? Math.Sin(x)/x : 1.0;
from http://msdn.microsoft.com/en-us/library/ty67wk28(v=vs.90).aspx
In Java, it's an if/else relationship.
An example of a ternary operation:
boolean bool = (x==1) ? true : false;
http://en.wikipedia.org/wiki/Ternary_operation
Is there any good alternative for the plain if statements in PHP? I know about switch, but I'll guess that there's some more refined alternative out there that comes handy when working with really big if statements.
Thanks a lot,
If you can't read your algorithm on one screen fold, there's a 99.9% chance you need to refactor your code toward more readability.
Change
if ($isHappening) {
// ... millions of lines of code
} else {
// .. another million lines of code
}
into
if ($isHappening) {
happen();
} else {
didntHappen();
}
function happen() {
// millions of lines of code
}
function didntHappen() {
// another million lines of code
}
There really is no magic hammer out there. Your best bet to making them manageable is to break nested ifs into their own functions to make them more readable.
Also, don't forget about array_filter. That can save you from having to write a for loop to filter out items.
Also, you can eliminate nesting by using guard statements. You basically invert your if and do a return instead (another reason to break conditions into functions).
If you want to improve readability only, then you can always split up the expressions inside the if statement:
$exp1 = is_array($var) && isset($var['key']);
$exp2 = is_object($var) && isset($var->key);
$exp3 = substr($string, 0, 4) == 'foo';
$exp4 = ($exp1 || $exp2) && $exp3;
if ($exp4) {}
instead of
if (((is_array($var) && isset($var['key'])) || (is_object($var) && isset($var->key))) && substr($string, 0, 4) == 'foo') {}
Obviously, these are simplified examples, but you get the idea...
Welcome to the world of Object Orientation :)
class Case1 {
function do() { echo "case 1"; }
}
class Case2 {
function do() { echo "case 2"; }
}
$object = new Case1();
$object->do();
And then, there is dispatching using an array:
$choices = array( "case1" => new Case1(), "case2" => new Case2(), ... );
$choices[ $_GET["case"] ]->do();
Well if is if, there is not much else out there. Of course switch is an alternative but depending on the conditions it might not be applicable.
If you are doing OOP, the state design pattern might be what you need.
Otherwise you have to give more information...
If by "big" you mean large, highly nested "ifs", this is a clear sign of code smell, and you should be looking at OOP and design patterns.
I'm working on modifying a script to better suit my needs, and I came across this line in the code:
return isset($_COOKIE[$parameter_name]) ? $_COOKIE[$parameter_name] : "";
I know that the function itself is essentially a cookie getter method, but I'm not quite sure what that syntax (i.e. the "?" and ":") means. I apologize if this is a really dumb question, but could someone explain it to me?
It's a ternary operation and is basically a more compact way of writing an if/then/else.
So in your code sample it's being used instead of having to write:
if (isset($_COOKIE[$parameter_name])) {
return $_COOKIE[$parameter_name];
} else {
return "";
}
It's a ternary operation which is not PHP specific and exists in most langauges.
(condition) ? true_case : false_case
And in my opinion should only be used as short one liners like in your example. Otherwise readabilty would suffer – so never nest ternary operation (though it's possible to do so).
The ? : are the ternary operator. Its a very quick if a then b else c:
if (a) { return b; } else { return c; }
is equivalent to:
return a ? b : c;
return isset($_COOKIE[$parameter_name]) ? $_COOKIE[$parameter_name] : "";
The function return:
$_COOKIE[$parameter_name]
If $_COOKIe with specified parameter_name exists, empty string otherwise.
Prototype:
condition ? this runs if condition true : this runs if condition false;
Let's say I have this code:
if (md5($_POST[$foo['bar']]) == $somemd5) {
doSomethingWith(md5($_POST[$foo['bar']]);
}
I could shorten that down by doing:
$value = md5($_POST[$foo['bar']];
if ($value == $somemd5) {
doSomethingWith($value);
}
But is there any pre-set variable that contains the first or second condition of the current if? Like for instance:
if (md5($_POST[$foo['bar']]) == $somemd5) {
doSomethingWith($if1);
}
May be a unnecessary way of doing it, but I'm just wondering.
No, but since the assignment itself is an expression, you can use the assignment as the conditional expression for the if statement.
if (($value = md5(..)) == $somemd5) { ... }
In general, though, you'll want to avoid embedding assignments into conditional expressions:
The code is denser and therefore harder to read, with more nested parentheses.
Mixing = and == in the same expression is just asking for them to get mixed up.
Since the if is just using the result of an expression, you can't access parts of it.
Just store the results of the functions in a variable, like you wrote in your second snippet.
IMHO your 2nd example (quoting below in case someone edits the question) is just ok. You can obscure the code with some tricks, but for me this is the best. In more complicated cases this advise may not apply.
$value = md5($_POST[foo['bar']];
if ($value) == $somemd5) {
doSomethingWith($value);
}