If .. Or Switch.

Which one is better? Are they used for different things?
Any pros or cons for each?

Or is it just a matter of which one you like best?

:)

IMHO, "Switch" is better if you have to qualify a variable with a lot of different possible values and each requires a different process.

"If" is better if you only have to test for a few possible values. A long list of If-ElseIf statements gets to be pretty hard to read sometimes.

I generally use "Switch" if I need to test for three or more possible values.

Like TopDogger said, switch is a bit more readable if you're going to branch code more than 3 ways depending on a value.

I would recommend you try using a "factory method" though if you have many different processes.
This is a bit of code that acts as a switch statement but does not get bulkier when you add more "switches".

/**
* Factory method example
*/
function factoryChoice($choice, $choices, $params = false) {
	if ( in_array($choice, $choices) ) {
		call_user_func($choice, $params);
	} else {
		echo 'Attempt to run arbitrary code!';
	} 
}

/**
* Example usage
*/
$choice = $_GET['choice'];
$choices = array('add', 'edit', 'delete');
$params = array($_GET['param1'], $_GET['param2'],$_GET['param3']);

factoryChoice($choice, $choices, $params);

What the factory method essensially does is take in a choice String, then matches it with predetermined choices Array. If the choice is allowed, it calls a functions of the same name as the choice.

What this does effectively is prevent you from hardcoding your switch statements, but instead allow a dynamic choices Array.
The dynamic choices Array can be fed from hardcoded values, like in the example, or read from a db etc.

You can even go further and set different access levels on your choices quite easily.
This would be much harder with hard coded switch or else/if statement.

Hope this still pertains to the topic. ;)

I use if more than switch.
It is a little common :)

I used a lot of if's, but lately I use them only for sub-section calling and use the switch() on handling the logic.

The good news is .. both will work just fine. Developer preference. :)

The big advantage to switch statements is that they make your code cleaner in appearance, and thusly easier to maintain. If you have more than two nested IF statements, it's probably time to use a switch.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.