Jump to content

Easier and more organized way than if/else if?


slyte33

Recommended Posts

Basically the title says it, but I know there is something with PHP easier than a bunch of lines a code than this:

 

If ($example == 1)
{
}else if ($example == 2)
{
}

 

I know you can make a function to do things easier, but that's selecting something from the DB and using loops.

Just a nice simple if/else if statement, is there an easier way, like 1 line of code or something?

 

It's a noob question, but I am just curious, thanks :)

switch($example){
case 1:
//stuff
break;
case 2:
//stuff
break;
}

 

Its called a switch/case statement

 

Thanks :)

With google I also found another way:

 

	$example = (($example2) > 0)?([dosomething?):dosomething?;

 

How does that work above?

That is called the ternary operators (? :) which is just a short if / else statement:

 

$example = ($example2 > 0)?'Greater Than 0!':'Less Than 0!';
echo $example;

 

So basically if example2 is greater than 0 set example to be "Greater Than 0!" else, set it to be "Less than 0!".

 

You cannot do anything more complex then an if/else with the ternary operator.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.