Operators, Conditionals, and PHP Decision-Making
(Page 1 of 4 )
In this second part of a three-part series on PHP, we wrap up our discussion of operators and introduce the topic of conditionals. This article is excerpted from chapter four of the book
Learning PHP and MySQL, Second Edition, written by Michele Davis and Jon Phillips (O'Reilly, 2006; ISBN: 0596101104). Copyright © 2006 O'Reilly Media, Inc. All rights reserved. Used with permission from the publisher. Available from booksellers or direct from O'Reilly Media.
Equality
The equality operator, a double equals sign (==), is used frequently. Using the single equals sign (=) in its place is a common logical error in programs, since it assigns values instead of testing equality.
If the two operands are equal, TRUE is returned; otherwise, FALSE is returned. If you're echoing your results, TRUE is printed as 1 in your browser. FALSE is 0 and won't display in your browser.
It's a simple construct, but it also allows you to test for conditions. If the operands are of different types, PHP attempts to convert them before comparing.
For example, '1'==1 is true. Also, $a==1 is true if the variable $a is assigned to 1.
If you don't want the equality operator to automatically convert types, you can use the identity operator, a triple equals sign (===), which checks whether the values and types are the same. For example, '1' === 1 is false because they're different types, since a string doesn't equal an integer.
Sometimes you might want to check to see whether two things are different. The inequality operator, an exclamation mark before the equals sign (!=), checks for the opposite of equality, which means that it is not equal to anything; therefore, it's FALSE.
'1' != 'A' // true
'1' != '1' // false
Comparison operators
You may need to check for more than just equality. Comparison operators test the relationship between two values. You may be familiar with these from high school math. They include less than (<), less-than or equal to (<=), greater than (>), and greater-than or equal to (>=).
For example, 3<4 is TRUE, while 3<3 is FALSE, and 3<=3 is TRUE.
Comparison operators are often used to check for something happening up until a set point. For example, an online store might offer free shipping if you purchase five or more items. So, the code must compare the number of items to the number five before changing the shipping cost.
Next: Logical operators >>
More Programming Basics Articles
More By O'Reilly Media
|
This article is excerpted from chapter four of the book Learning PHP and MySQL, Second Edition, written by Michele Davis and Jon Phillips (O'Reilly, 2006; ISBN: 0596101104). Check it out today at your favorite bookstore. Buy this book now.
|
|