Industrial
Industrial

Reputation: 42788

Dealing with big IF statements in 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,

Upvotes: 1

Views: 3148

Answers (6)

Cristian Rodriguez
Cristian Rodriguez

Reputation: 629

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.

Upvotes: 1

ircmaxell
ircmaxell

Reputation: 165261

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...

Upvotes: 5

xtofl
xtofl

Reputation: 41519

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

Upvotes: 3

Fletcher Moore
Fletcher Moore

Reputation: 13814

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
}

Upvotes: 13

Felix Kling
Felix Kling

Reputation: 816790

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...

Upvotes: 1

ryeguy
ryeguy

Reputation: 66851

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).

Upvotes: 5

Related Questions