Before we get started with conditions, let’s take a quick look at comparison operators. You should remember them from math class. These allow you to make a comparison between two values. For instance, 1 is less than 2, $a equals $b, or $a is not equal to ‘dude bro’.
The full list is:
== != < > <= >=
Programming is all about conditions. Hell, life is all about conditions. We think in conditions, right? Like when you think, IF I wear aviators, THEN I will look badass. Noone said you’re logic is always correct, but hey, you get the idea.
So how does this work in PHP? Well, we have if else statements to do this. Let’s go through one.
Here we have the if statement, the bread and butter of programming.
if ($cashmoney > 100) { print(‘hit up the strip club’); } elseif ($cashmoney > 10) { print(‘buy beer’); } else { print(‘fap, sleep’); }
Start with the if keyword, then parenthesis, inside those we’ll put our condition, cash money is greater than 100. Follow that with some braces, then print hit up the strip club. Next, we’ll put elseif cash money is greater than 10, buy some beer to soak up your sadness. The else statement comes last, if all of our conditions fail. Maybe you should get a job with your new programming skills.
But what if you have A LOT of options, like I do, you know, cause I’m a total babe, and sort of a genius. Well, you could have a huge if and else if statement OR you could use the switch statement. It’s a little more complicated, but easier to read.
Let’s do one.
$os = “OSX”; switch ($os) { case “OSX”: print “I’m a mac ”; break; case ‘PC’: print “I’m a PC”; break; case ‘Linux’: print “Oh, look, we’ve got a bad ass over here.”; break; default: print “3rd world bitches”; break; }
So how does this work? The switch statement takes a variable and then compares that too a bunch of different values. If the variable matches the case it will execute the code block of that case.
In the example we switch our cases based on the operating system given. If the statement is given OSX position it will print the text ‘fanboy’.
If nothing matches you’ll get the default. How did you get here, you’re phone?
Important to note is that PHP will continue executing after the first case is matched. Usually, we don’t want that, so we add a break statement after each case block. The break statement will jump us out of the switch statement.
Next we’ll get really freaky with arrays.
Questions or Comments?