Dealing with big IF statements in PHP - php

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.

Related

More elegant way to write these conditions?

out of curiosity I'm wondering if there's a more elegant way to write the conditionals below? I can't see a shorter way of writing it but it feels pretty clunky, so any suggestions welcome!
// Check whether this page has any visuals
if (count($this->page->pagevisuals->find_all()) > 0)
{
// Ok to go ahead and assign
$visual = $this->page->pagevisuals->find_all();
}
// If this is a sub page, parent page may have visuals we can use
elseif (count($this->page->parent->pagevisuals->find_all()) > 0)
{
$visual = $this->page->parent->pagevisuals->find_all();
}
// If two levels deep, grandparent page might have visuals
elseif (count($this->page->parent->parent->pagevisuals->find_all()) > 0)
{
$visual = $this->page->parent->parent->pagevisuals->find_all();
}
You can write a loop instead:
$page = $this->page;
$visual = null;
while (!$visual && $page) {
$visual = $page->pagevisuals->find_all();
$page = $page->parent;
}
I believe this is equivalent, and will work no matter how many levels of parents/nesting you have.
You could assign $this->page to a variable and begin the statements with that, for a very slight improvement.
Alternatively, you could create nested ternary statements to assign $visual, but that's certainly not recommended practice.
A recursive approach:
function getVisuals($root) {
$visuals = $root->pagevisuals->find_all();
if(count($visuals) === 0 && isset($root->parent)) {
$visuals = getVisuals($root->parent);
}
return $visuals;
}
$visuals = getVisuals($this->page);
If you have control over whatever class $this->page is an instance of, then you can make it an instance method.
You could make a recursive method to get rid of those nasty conditionals. Also you're calling the find_all() method twice for every conditional branch which doubles the process time.
Here's an attempt at a recursive function (might not work though, recursive functions are always a bit tricky!). Beware of infinite loops.
<?php
$visual = $this->page->find_all_visuals();
class Page {
function find_all_visuals()
{
$found = $this->pagevisuals->find_all();
if (count($found) > 0) {
return $found;
} else if ($this->parent == null) {
return null;
} else {
return $this->parent->find_all_visuals();
}
}
}
?>
You might want make two changes in your code:
Ensure that getVisuals() returns an empty array instead of null in case there are no visuals
Consider making a null-object - a singleton page instance that has no visuals and has itself as a parent. It might have a method like isNull() so you can easily test if a given page is the null page.
If you make the two adjustments, most of the code concerning visuals will become easier to write and debug.
Getting all the visuals for two levels (I assume you don't want recursion):
$visuals = array_merge(
$this->page->pagevisuals->find_all(),
$this->page->parent->pagevisuals->find_all(),
$this->page->parent->parent->pagevisuals->find_all(),
);
Getting the visuals of the page OR of parent OR of grand parent:
($visuals = $this->page->pagevisuals->find_all()) ||
($visuals = $this->page->parent->pagevisuals->find_all()) ||
($visuals = $this->page->parent->parent->pagevisuals->find_all());
Recursive functions would be much simpler too (this is a method to add to the page object):
public function findRecursive(){
$my_visuals = $this->pagevisuals->find_all()
return $this->parent->isNull()?
$my_visuals
: array_merge($my_visuals, $this->parent->findRecursive());
}
$visual = $this->page->pagevisuals->find_all()
or $visual = $this->page->parent->pagevisuals->find_all()
or $visual = $this->page->parent->parent->pagevisuals->find_all();
What do you do if none of them match? In this code it will be set to the last one, which is not the same as what you did. (In your code $visual was not touched if none matched, in this code it will be set to zero. You could add or $visual = -1 or something similar.)
You can make a loop if you want to avoid all the ->parent, but you'll need some terminator.
$el = $this->page;
while(!$visual = $el->pagevisuals->find_all()) {
$el = $el->parent;
}
This could run forever if it never matches, but I don't know enough about your application to suggest a termination condition - you could add a counter, or something else.

Is this the way to do this simple IF OR OR statement?

I have an if statement with a few or's in it.
i.e.
if($count == 1 || $count == 3 || $count == 7) {
// do stuff
}
I'm just curious - is this the best way to do this? With this simple example above, is there a faster way to do this, and if so, what is it?
Your code works fine. Alternately, you can use in_array(), which is a bit cleaner and scales better:
if (in_array($count, array(1,3,7))) { ... }
The code you've written is fine. As Paul Schreiber says, there are various other options that are a little neater.
One thing you may want to think about (and I know this is just an example) is why the values you're checking are important. Do they all have some property in common that you're checking? If so, then stating the property symbolically may make the code easier for someone to understand. For example:
if (is_odd($x) && $x < 10) {
//...
}
rather than
if ($x == 1 || $x == 3 || $x == 5 || $x == 7 || $x == 9 ) {
//...
}
This is quite a contrived example, but hopefully you see what I'm getting at.
As a more concrete example, instead of doing something like:
if ($user->age > 65
|| $user->years_of_custom > 3
|| $num_items > 5 ) {
// Give this user a discount ....
}
you might want to do:
if (eligible_for_discount($user, $num_items) ) {
// Give this user a discount
}
Even if you only use the function in this one place, this could increase the readability of the code. Obviously you have to use your judgment though, because you're increasing readability at the expense of having more lines of code to maintain, and that isn't always the right choice. If the conditions have little to do with each other, binding them up into a separate function might make no sense and make your code harder to follow, not easier. Focus on what your code actually means, and how a human being should understand it.
You can assign all possible value in an array and check using array_search function
$array=array(1,3,7);
if (array_search($count,$array) !== FALSE)
{
//do stuff
}
Wouldn't the switch statement be better?
switch ($count) {
case 1:
case 3:
case 7:
echo "do stuff";
break;
}

refactoring this block

I'm refactoring some code that wasn't written by me. This block sets the value of $val but I want to clean it up a bit. Obviously I can't use the tertiary operator here. What other ways I can make this code cleaner?
if (isset($vars[$input])) {
$val = $vars[$input];
} elseif (isset($this->getI['io'])) {
$val = $this->getI['io'];
} elseif (isset($vars[5])) {
$val = $vars[5];
} else {
$val = 10;
}
$val = 10;
if (isset($vars[$input])) {
$val = $vars[$input];
} elseif (isset($this->getI['io'])) {
$val = $this->getI['io'];
} elseif (isset($vars[5])) {
$val = $vars[5];
}
This is about as simple as it gets without obfuscating the code. I'd rather try to simplify the logic, it's kinda hard to comprehend why the value is being looked for in so many different places.
I'm afraid I don't know php. I'm assuming that if you were to pass (say) $vars[$input] to a function, by the time it was a parameter to the function, the parameter's set-ness would be true (if that's not the case, I'd try writing a function that tested isset() on its parameter and set $val if so). I find elseif's to add complexity; I try to avoid them. In this case, I would write a function that returned the value; then all my elseif's can become plain if's.
f() {
if (isset($vars[$input])) {
return $vars[$input];
}
if (isset($this->getI['io'])) {
return $this->getI['io'];
}
if (isset($vars[5])) {
return $vars[5];
}
return 10;
}
And, of course, in your calling function, assign $val to the result of this function.
In my opinion, your example is as clean as it gets. Sure, you could write it as a huge one-liner using the ternary operator:
$val = isset($vars[$input]) ? $vars[$input] : isset($this->getI['io'] ? $this->getI['io'] : isset($vars[5]) ? $vars[5] : 10;
But this is obviously much harder to read and to maintain, so the original example is definitely cleaner (although it might be missing some comments).
I don't know...it seems to be pretty concise, as is.
If you know what it does, it does it well and it is clean enough that you can figure it out again in the future, I say don't touch it.
While you're at it figure out what it's doing and add some comments.
e.g. why assign it to the magic number 10? maybe the context of the rest of it may shed some light.
As far as code goes, you're not going to get it any simpler than this.

Do you consider foreach((array)$foo as $bar) a code smell?

Do you consider this a code smell?
foreach((array)$foo as $bar)
{
$bar->doStuff();
}
Should i use that instead?
if (isset($foo) && is_array($foo))
{
foreach($foo as $bar)
{
$bar->doStuff();
}
}
Any other good practices to cover not set variables and assert an array?
They're both code smells. The second one is just evading all the error messages, kind of like turning off the fire alarm before you set your kitchen on fire. Both of those tell you that you have no idea what's in the variable $foo or if it's even been defined in the code above. You need to go back up through the code and find out exactly what's going on with $foo.
If it was my code, $foo would probably be always defined either as an array, or else false to indicate the array isn't needed:
if(do_we_need_an_array())
$foo = function_returning_an_array();
else
$foo = false;
[...snip...]
if($foo)
foreach($foo as $f) { ... }
If you are testing if variables are set, you can initialize them:
if (! $foo or !is_array($foo))
$foo = array();
foreach($foo as $bar)
{
$bar->doStuff();
}
Personally, I would never do the first method and always opt for the second.
If $foo should always be an array, then the second form would be much better if you did some kind of handling for the error case, e.g.:
if (isset($foo) && is_array($foo))
{
foreach($foo as $bar)
{
$bar->doStuff();
}
}
else
{
// This should not happen, exit angrily.
exit("Oh crap, foo isn't an array!");
}
Of course you don't have to just exit the application, but do whatever is appropriate in that case, maybe logging or some alternate logic.
(array)$foo != if (isset($foo) && is_array($foo))
The (array) cast can be useful for casting objects to arrays or scalars to arrays so you can create consistent interfaces to variables that may contain single values or arrays.
(array)$foo == array($foo)
As defined in the PHP Manual for Array Types.
So if you need to always use an array then the first code snippet you presented would be the answer. However type casting rules still apply so you may not get what you want, so look to the manual for more info. Otherwise the second option would prevent accessing unset variables that are not arrays.
As far as a code smell, I would say that checking for unset variables can certainly be avoided, however always knowing that a variable is going to have an array is more often than not, going to creep up. So I would aim to keep code wrapped in is_array($foo) if-then statements to a minimum.
I usually do this to make sure a foreach can handle both scalars and collections:
<?php
foreach (makeSureTraversable($scalarOrCollection) as $val)
{
// Do something.
}
function
makeSureTraversable($anything)
{
if (is_array($anything) || ($anything instanceof Traversable))
{
return $anything;
}
else
{
return array($anything);
}
}
This way I also handle classes that implement Traversable (from the SPL), which means allowing them to be used in foreaches.
if (!isset($foo) && !is_array($foo)) {
throw new InvalidArgumentException('Wrong array passed');
// Or do something to recover lost array
}
foreach($foo as $bar) {
$bar->doStuff();
}
There's quite a few times that you'd like to write a function to take one or more values for a parameter:
function getNamesById($id) { }
In this case, it would make sense that if this function was called with an array of ids, it should probably return an array of names. Similarly, to save the calling code from having to wrap the input in an array and then unwrap the output, if you just pass a scalar, then a scalar should be returned. Consider the likely contents of the function designed to handle both scalar and array parameters:
function getNamesById($id) {
$returnAnArray = is_array($id);
$output = array();
foreach ((array)$id as $theId) {
// perform some logic
$output[] = someFunction($theId);
}
return $returnAnArray ? $output : $output[0];
}
You can see that in this case, casting to an array definitely makes things a lot easier for everyone. As they say, be liberal in what you accept... As long as it is documented that it is expected that a variable could be either, then I see no problem. PHP is a duck-typed language, which has both benefits and drawbacks, but this is one of the benefits, so enjoy it!

PHP: return a part of an if () { }

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

Categories