As well as the PHP comparison operators you saw earlier, there's also something called Logical Operators. You typically use these when you want to test more than one condition at a time. For example, you could check to see whether the username and password are correct from the same If Statement. Here's the table of these Operands.
Operand Example Meaning
&& $variable1 && $variable2 Are both values true?
| | $variable1 | | $variable2 Is at least one value true?
AND $variable1 AND $variable2 Are both values true?
XOR $variable1 XOR $variable2 Is at least one value true, but NOT both?
OR $variable1 OR $variable2 Is at least one value true?
! !$variable1 Is NOT something
The new Operands are rather strange, if you're meeting them for the first time. A couple of them even do the same thing! They are very useful, though, so here's a closer look.
The && Operator
The && symbols mean AND. Use this if you need both values to be true, as in our username and password test. After all, you don't want to let people in if they just get the username right but not the password! Here's an example:
$username ='user';
$password ='password';
if ($username ='user' && $password ='password') {
print("Welcome back!");
}
else {
print("Invalid Login Detected");
}
The if statement is set up the same, but notice that now two conditions are being tested:
$username ='user' && $password ='password
This says, "If username is correct AND the password is ok, too, then let them in". Both conditions need to go between the round brackets of your if statement.
The | | Operator
The two straight lines mean OR. Use this symbol when you only need one of your conditions to be true. For example, suppose you want to grant a discount to people if they have spent more than 100 pounds OR they have a special key. Else they don't get any discount. You'd then code like this:
$total_spent =100;
$special_key ='SK12345';
if ($total_spent =100 | | $special_key ='SK12345') {
print("Discount Granted!");
}
else {
print("No discount for you!");
}
This time we're testing two conditions and only need ONE of them to be true. If either one of them is true, then the code gets executed. If they are both false, then PHP will move on.
AND and OR
These are the same as the first two! AND is the same as && and OR is the same as ||. There is a subtle difference, but as a beginner, you can simply replace this:
$username ='user' && $password ='password
With this
$username ='user' AND $password ='password
And this:
$total_spent =100 | | $special_key ='SK12345'
With this:
$total_spent =100 OR $special_key ='SK12345'
It's up to you which you use. AND is a lot easier to read than &&. OR is a lot easier to read than ||.
The difference, incidentally, is to do with Operator Precedence. We touched on this when we discussed variables, earlier. Logical Operators have a pecking order, as well. The full table is coming soon!
XOR
You probably won't need this one too much. But it's used when you want to test if one value of two is true but NOT both. If both values are the same, then PHP sees the expression as false. If they are both different, then the value is true. Suppose you had to pick a winner between two contestants. Only one of them can win. It's an XOR situation!
$contestant_one = true;
$contestant_two = true;
if ($contestant_one XOR $contestant_two) {
print("Only one winner!");
}
else {
print("Both can't win!");
}
See if you can guess which of the two will print out, before running the script.
The ! Operator
This is known as the NOT operator. You use it test whether something is NOT something else. You can also use it to reverse the value of a true or false value. For example, you want to reset a variable to true, if it's been set to false, and vice versa. Here's some code to try:
$test_value = false;
if ($test_value = = false) {
print(!$test_value);
}
The code above will print out the number 1! (You'll see why when we tackle Boolean values below.) What we're saying here is, "If $test_value is false then set it to what it's NOT." What it's NOT is true, so it will now get this value. A bit confused? It's a tricky one, but it can come in handy!
In the next part, we'll take a look at Boolean values.
Monday, January 7, 2008
The PHP Switch Statement
$picture ='church';
switch ($picture) {
case 'kitten':
print('Kitten Picture');
break;
case 'church':
print('Church Picture');
break;
}
?>
In the code above, we place the direct text "church" into the variable called $picture. It's this direct text that we want to check. We want to know what is inside of the variable, so that we can display the correct picture.
To test a single variable with a Switch Statement, the following syntax is used:
switch ($variable_name) {
case 'What_you_want_to_check_for':
//code here
break;
}
It looks a bit complex, so we'll break it down.
switch ($variable_name) {
You Start with the word 'Switch' then a pair of round brackets. Inside of the round brackets, you type the name of the variable you want to check. After the round brackets, you need a left curly bracket.
case 'What_you_want_to_check_for':
The word 'case' is used before each value you want to check for. In our code, a list of values was coming from a drop-down list. These value were: church and kitten, among others. These are the values we need after the word 'case'. After the the text or variable you want to check for, a colon is needed ( : ).
//code here
After the semi colon on the 'case' line, you type the code you want to execute. Needless to say, you'll get an error if you miss out any semi-colons at the end of your lines of code!
break;
You need to tell PHP to "Break out" of the switch statement. If you don't, PHP will simply drop down to the next case and check that. Use the word 'break' to get out of the Switch statement.
To see the Switch statement in action, there is a file called "selectPicture2.php" amongst the ones you downloaded (Go here, if you haven't yet downloaded the files for this course). It’s in the scripts folder. Try it out, if you like!
If you look at the last few lines of the Switch Statement in this file, you'll see something else you can add to your own code:
default:
print ("No Image Selected");
The default option is like the else from if … else. It's used when there could be other, unknown, options. A sort of "catch all" option.
What these mean: <= >=
$total_spent = 90;
to this:
$total_spent = 100;
Now run your code again. Did anything print?
The reason why nothing printed, and no errors occurred, is because we haven't written any condition logic to test for equality. We're only checking to see if the two variables are either Less Than ( < ) each other, or Greater Than ( > ) each other. We need to check if they are the same (as they now are).
Instead of adding yet another else if part, checking to see if the two totals are equal, we can use the operators <= (Less Than or Equal To) or >= (Greater Than or Equal To). Here's how. Change this line in your code:
else if($total_spent < $discount_total) {
to this:
else if($total_spent <= $discount_total) {
The only thing that's changed is the Less Than or Equal to symbol has been used instead of just the Less Than sign.
Now run your code again. Because we're now saying "If total spent is Less Than or equal to discount total, then execute the code." So the text gets printed to the screen.
to this:
$total_spent = 100;
Now run your code again. Did anything print?
The reason why nothing printed, and no errors occurred, is because we haven't written any condition logic to test for equality. We're only checking to see if the two variables are either Less Than ( < ) each other, or Greater Than ( > ) each other. We need to check if they are the same (as they now are).
Instead of adding yet another else if part, checking to see if the two totals are equal, we can use the operators <= (Less Than or Equal To) or >= (Greater Than or Equal To). Here's how. Change this line in your code:
else if($total_spent < $discount_total) {
to this:
else if($total_spent <= $discount_total) {
The only thing that's changed is the Less Than or Equal to symbol has been used instead of just the Less Than sign.
Now run your code again. Because we're now saying "If total spent is Less Than or equal to discount total, then execute the code." So the text gets printed to the screen.
Not Equal To
$correct_username = 'logmein';
$what_visitor_typed = 'logMEin';
if ($what_visitor_typed != $correct_username) {
print("You're not a valid user of this site!");
}
?>
Save your work and try it out. You should be able to guess what it does! But the thing to note here is the new Comparison Operator. Instead of using the double equals sign we’re now using an exclamation mark and a single equals sign. The rest of the If Statement is exactly the same format as you used earlier.
The things you’re trying to compare need to be different before a value of true is returned by PHP. In the second variable ($what_visitor_typed), the letters “ME” are in uppercase; in the first variable, they are in lowercase. So the two are not the same. Because we used the NOT equal to operator, the text will get printed. Change your script to this:
$correct_username = 'logmein';
$what_visitor_typed = 'logmein';
if ($what_visitor_typed != $correct_username) {
print("You're not a valid user of this site!");
}
else {
print("Welcome back, friend!");
}
Comparison Operators in PHP
You saw in the last section how to test what is inside of a variable. You used if, else … if, and else. You used the double equals sign (==) to test whether the variable was the same thing as some direct text. The double equals sign is known as a Comparison Operator. There a few more of these “operands” to get used. Here’s a list. Take a look, and then we’ll see a few examples of how to use them.
Operand Example Meaning
== $variable1 == $variable2 Has the same value as
!= $variable1 != $variable2 Does NOT have the same value as
< $variable1 < $variable2 Less Than
> $variable1 > $variable2 Greater Than
<= $variable1 <= $variable2 Less than or equals to
>= $variable1 >= $variable2 Greater than or equals to
Here's some more information on the above Operands.
= = (Has the same value as)
The double equals sign can mean “Has a value of” or "Has the same value as”. In the example below, the variable called $variable1 is being compared to the variable called $variable2
if ($variable1 == $variable2) {
}
!= (Does NOT have the same value as)
You can also test if one condition is NOT the same as another. In which case, you need the exclamation mark/equals sign combination ( != ). If you were testing for a genuine username, for example, you could say:
if ($what_user_entered != $username) {
print("You're not a valid user of this site!")
}
The above code says, “If what the user entered is NOT the same as the value in the variable called $username then print something out.
< (Less Than)
You'll want to test if one value is less than another. Use the left angle bracket for this ( < )
> (Greater Than)
You'll also want to test if one value is greater than another. Use the right angle bracket for this ( > )
<= (Less than or equals to)
For a little more precision, you can test to see if one variable is less than or equal to another. Use the left angle bracket followed by the equals sign ( <= )
>= (Greater than or equals to)
If you need to test if one variable is greater than or equal to another, use the right angle bracket followed by the equals sign ( >= )
Operand Example Meaning
== $variable1 == $variable2 Has the same value as
!= $variable1 != $variable2 Does NOT have the same value as
< $variable1 < $variable2 Less Than
> $variable1 > $variable2 Greater Than
<= $variable1 <= $variable2 Less than or equals to
>= $variable1 >= $variable2 Greater than or equals to
Here's some more information on the above Operands.
= = (Has the same value as)
The double equals sign can mean “Has a value of” or "Has the same value as”. In the example below, the variable called $variable1 is being compared to the variable called $variable2
if ($variable1 == $variable2) {
}
!= (Does NOT have the same value as)
You can also test if one condition is NOT the same as another. In which case, you need the exclamation mark/equals sign combination ( != ). If you were testing for a genuine username, for example, you could say:
if ($what_user_entered != $username) {
print("You're not a valid user of this site!")
}
The above code says, “If what the user entered is NOT the same as the value in the variable called $username then print something out.
< (Less Than)
You'll want to test if one value is less than another. Use the left angle bracket for this ( < )
> (Greater Than)
You'll also want to test if one value is greater than another. Use the right angle bracket for this ( > )
<= (Less than or equals to)
For a little more precision, you can test to see if one variable is less than or equal to another. Use the left angle bracket followed by the equals sign ( <= )
>= (Greater than or equals to)
If you need to test if one variable is greater than or equal to another, use the right angle bracket followed by the equals sign ( >= )
if … else if Statements in PHP
else if (another_condition_to_test) {
}
Change your code to this, to see how else if works:
$kitten_image = 1;
$church_image = 0;
if ($kitten_image == 1) {
print ("
");
}
else if ($church_image == 1){
print ("
");
}
else {
print ("No value of 1 detected");
}
?>
Here’s we’re just testing to see which of our variables holds a value of 1. But notice the “else if” lines (and that there’s a space between else and if):
else if ($church_image == 1){
print ("
");
}
What you’re saying is “If the previous if statement isn’t true, then try this one.” PHP will then try to evaluate the new condition. If it’s true (the $church_image variable holds a value of 1), then the code between the new curly brackets gets executes. If it’s false (the $church_image variable does NOT holds a value of 1), then the line of code will be ignored, and PHP will move on.
To catch any other eventualities, we have an “else” part at the end. Notice that all parts (if, else if, and else) are neatly sectioned of with pairs of curly brackets:
if ($kitten_image == 1) {
}
else if ($church_image == 1) {
}
else {
}
You can add as many else if parts as you like, one for each condition that you want to test. But change your two variables from this:
$kitten_image = 1;
$church_image = 0;
to this:
$kitten_image = 0;
$church_image = 0;
}
Change your code to this, to see how else if works:
$kitten_image = 1;
$church_image = 0;
if ($kitten_image == 1) {
print ("

}
else if ($church_image == 1){
print ("

}
else {
print ("No value of 1 detected");
}
?>
Here’s we’re just testing to see which of our variables holds a value of 1. But notice the “else if” lines (and that there’s a space between else and if):
else if ($church_image == 1){
print ("

}
What you’re saying is “If the previous if statement isn’t true, then try this one.” PHP will then try to evaluate the new condition. If it’s true (the $church_image variable holds a value of 1), then the code between the new curly brackets gets executes. If it’s false (the $church_image variable does NOT holds a value of 1), then the line of code will be ignored, and PHP will move on.
To catch any other eventualities, we have an “else” part at the end. Notice that all parts (if, else if, and else) are neatly sectioned of with pairs of curly brackets:
if ($kitten_image == 1) {
}
else if ($church_image == 1) {
}
else {
}
You can add as many else if parts as you like, one for each condition that you want to test. But change your two variables from this:
$kitten_image = 1;
$church_image = 0;
to this:
$kitten_image = 0;
$church_image = 0;
if … else Statements in PHP
$kitten_image = 0;
$church_image = 1;
if ($kitten_image == 1) {
print ("

}
else {
print ("

}
?>
Copy this new script, save your work, and try it out. You should find that the church image displays in the browser. This time, an if … else statement is being used. Let’s see how it works.
The syntax for the if else statement is this:
if (condition_to_test) {
}
else {
}
If you look at it closely, you’ll see that you have a normal If Statement first, followed by an “else” part after it. Here’s the “else” part:
else {
}
Again, the left and right curly brackets are used. In between the curly brackets, you type the code you want to execute. In our code, we set up two variables:
$kitten_image = 0;
$church_image = 1;
The variable called $kitten_image has been assigned a value of 0, and the variable called $church_image has been assigned a value of 1. The first line of the if statement tests to see what is inside of the variable called $kitten_image. It’s testing to see whether this variable has a value of 1.
if ($kitten_image == 1) {
What we’re asking is: “Is it true that $kitten_image holds a value of 1?” The variable $kitten_image holds a value of 0, so PHP sees this as not true. Because a value of “not true” has been returned (false, if you like), PHP ignores the line of code for the if statement. Instead, it will execute the code for the “else” part. It doesn’t need to do any testing – else means “when all other options have been exhausted, run the code between the else curly brackets.“ For us, that was this:
else {
print ("

}
So the church image gets displayed. Change your two variables from this:
$kitten_image = 0;
$church_image = 1;
To this:
$kitten_image = 1;
$church_image = 0;
Subscribe to:
Posts (Atom)