You are previewing Learning PHP, MySQL, JavaScript, and CSS, 2nd Edition.

Learning PHP, MySQL, JavaScript, and CSS, 2nd Edition

Cover of Learning PHP, MySQL, JavaScript, and CSS, 2nd Edition by Robin Nixon Published by O'Reilly Media, Inc.
  1. Learning PHP, MySQL, JavaScript, and CSS
  2. Dedication
  3. Preface
    1. Audience
    2. Assumptions This Book Makes
    3. Organization of This Book
    4. Supporting Books
    5. Conventions Used in This Book
    6. Using Code Examples
    7. Safari® Books Online
    8. How to Contact Us
    9. Acknowledgments
  4. 1. Introduction to Dynamic Web Content
    1. HTTP and HTML: Berners-Lee’s Basics
      1. The Request/Response Procedure
    2. The Benefits of PHP, MySQL, JavaScript, and CSS
      1. Using PHP
      2. Using MySQL
      3. Using JavaScript
      4. Using CSS
    3. The Apache Web Server
    4. About Open Source
    5. Bringing It All Together
    6. Test Your Knowledge
  5. 2. Setting Up a Development Server
    1. What Is a WAMP, MAMP, or LAMP?
    2. Installing a WAMP on Windows
      1. Testing the Installation
      2. Alternative WAMPs
    3. Installing a MAMP on OS X
      1. Configuring MySQL
      2. Testing the Installation
    4. Installing a LAMP on Linux
    5. Working Remotely
      1. Logging In
      2. Using FTP
    6. Using a Program Editor
    7. Using an IDE
    8. Test Your Knowledge
  6. 3. Introduction to PHP
    1. Incorporating PHP Within HTML
      1. Calling the PHP Parser
    2. This Book’s Examples
    3. The Structure of PHP
      1. Using Comments
      2. Basic Syntax
      3. Understanding Variables
      4. Operators
      5. Variable Assignment
      6. Multiple-Line Commands
      7. Variable Typing
      8. Constants
      9. The Difference Between the echo and print Commands
      10. Functions
      11. Variable Scope
    4. Test Your Knowledge
  7. 4. Expressions and Control Flow in PHP
    1. Expressions
      1. Literals and Variables
    2. Operators
      1. Operator Precedence
      2. Associativity
      3. Relational Operators
    3. Conditionals
      1. The if Statement
      2. The else Statement
      3. The elseif Statement
      4. The switch Statement
      5. The ? Operator
    4. Looping
      1. while Loops
      2. do…while Loops
      3. for Loops
      4. Breaking Out of a Loop
      5. The continue Statement
    5. Implicit and Explicit Casting
    6. PHP Dynamic Linking
      1. Dynamic Linking in Action
    7. Test Your Knowledge
  8. 5. PHP Functions and Objects
    1. PHP Functions
      1. Defining a Function
      2. Returning a Value
      3. Returning an Array
      4. Passing by Reference
      5. Returning Global Variables
      6. Recap of Variable Scope
    2. Including and Requiring Files
      1. The include Statement
      2. Using include_once
      3. Using require and require_once
    3. PHP Version Compatibility
    4. PHP Objects
      1. Terminology
      2. Declaring a Class
      3. Creating an Object
      4. Accessing Objects
      5. Constructors
      6. Writing Methods
      7. Declaring Properties
      8. Declaring Constants
      9. Property and Method Scope in PHP 5
      10. Inheritance
    5. Test Your Knowledge
  9. 6. PHP Arrays
    1. Basic Access
      1. Numerically Indexed Arrays
      2. Associative Arrays
      3. Assignment Using the array Keyword
    2. The foreach...as Loop
    3. Multidimensional Arrays
    4. Using Array Functions
      1. is_array
      2. count
      3. sort
      4. shuffle
      5. explode
      6. extract
      7. compact
      8. reset
      9. end
    5. Test Your Knowledge
  10. 7. Practical PHP
    1. Using printf
      1. Precision Setting
      2. String Padding
      3. Using sprintf
    2. Date and Time Functions
      1. Date Constants
      2. Using checkdate
    3. File Handling
      1. Checking Whether a File Exists
      2. Creating a File
      3. Reading from Files
      4. Copying Files
      5. Moving a File
      6. Deleting a File
      7. Updating Files
      8. Locking Files for Multiple Accesses
      9. Reading an Entire File
      10. Uploading Files
    4. System Calls
    5. XHTML
      1. The Benefits of XHTML
      2. XHTML Versions
      3. What’s Different?
      4. HTML 4.01 Document Types
      5. The HTML5 Document Type
      6. XHTML 1.0 Document Types
      7. XHTML Validation
    6. Test Your Knowledge
  11. 8. Introduction to MySQL
    1. MySQL Basics
    2. Summary of Database Terms
    3. Accessing MySQL via the Command Line
      1. Starting the Command-Line Interface
      2. Using the Command-Line Interface
      3. MySQL Commands
      4. Data Types
    4. Indexes
      1. Creating an Index
      2. Querying a MySQL Database
      3. Joining Tables Together
      4. Using Logical Operators
    5. MySQL Functions
    6. Accessing MySQL via phpMyAdmin
      1. Windows Users
      2. OS X Users
      3. Linux Users
      4. Using phpMyAdmin
    7. Test Your Knowledge
  12. 9. Mastering MySQL
    1. Database Design
      1. Primary Keys: The Keys to Relational Databases
    2. Normalization
      1. First Normal Form
      2. Second Normal Form
      3. Third Normal Form
      4. When Not to Use Normalization
    3. Relationships
      1. One-to-One
      2. One-to-Many
      3. Many-to-Many
      4. Databases and Anonymity
    4. Transactions
      1. Transaction Storage Engines
      2. Using BEGIN
      3. Using COMMIT
      4. Using ROLLBACK
    5. Using EXPLAIN
    6. Backing Up and Restoring
      1. Using mysqldump
      2. Creating a Backup File
      3. Restoring from a Backup File
      4. Dumping Data in CSV Format
      5. Planning Your Backups
    7. Test Your Knowledge
  13. 10. Accessing MySQL Using PHP
    1. Querying a MySQL Database with PHP
      1. The Process
      2. Creating a Login File
      3. Connecting to MySQL
    2. A Practical Example
      1. The $_POST Array
      2. Deleting a Record
      3. Displaying the Form
      4. Querying the Database
      5. Running the Program
    3. Practical MySQL
      1. Creating a Table
      2. Describing a Table
      3. Dropping a Table
      4. Adding Data
      5. Retrieving Data
      6. Updating Data
      7. Deleting Data
      8. Using AUTO_INCREMENT
      9. Performing Additional Queries
      10. Preventing SQL Injection
      11. Preventing HTML Injection
    4. Test Your Knowledge
  14. 11. Form Handling
    1. Building Forms
    2. Retrieving Submitted Data
      1. register_globals: An Old Solution Hangs On
      2. Default Values
      3. Input Types
      4. Sanitizing Input
    3. An Example Program
    4. Test Your Knowledge
  15. 12. Cookies, Sessions, and Authentication
    1. Using Cookies in PHP
      1. Setting a Cookie
      2. Accessing a Cookie
      3. Destroying a Cookie
    2. HTTP Authentication
      1. Storing Usernames and Passwords
      2. Salting
    3. Using Sessions
      1. Starting a Session
      2. Ending a Session
      3. Session Security
    4. Test Your Knowledge
  16. 13. Exploring JavaScript
    1. JavaScript and HTML Text
      1. Using Scripts Within a Document Head
      2. Older and Nonstandard Browsers
      3. Including JavaScript Files
      4. Debugging JavaScript Errors
    2. Using Comments
    3. Semicolons
    4. Variables
      1. String Variables
      2. Numeric Variables
      3. Arrays
    5. Operators
      1. Arithmetic Operators
      2. Assignment Operators
      3. Comparison Operators
      4. Logical Operators
      5. Variable Incrementing and Decrementing
      6. String Concatenation
      7. Escaping Characters
    6. Variable Typing
    7. Functions
    8. Global Variables
      1. Local Variables
    9. The Document Object Model (DOM)
      1. But It’s Not That Simple
      2. Using the DOM
    10. Test Your Knowledge
  17. 14. Expressions and Control Flow in JavaScript
    1. Expressions
      1. Literals and Variables
    2. Operators
      1. Operator Precedence
      2. Associativity
      3. Relational Operators
    3. The with Statement
    4. Using onerror
    5. Using try...catch
    6. Conditionals
      1. The if Statement
      2. The switch statement
      3. The ? Operator
    7. Looping
      1. while Loops
      2. do…while Loops
      3. for Loops
      4. Breaking Out of a Loop
      5. The continue Statement
    8. Explicit Casting
    9. Test Your Knowledge
  18. 15. JavaScript Functions, Objects, and Arrays
    1. JavaScript Functions
      1. Defining a Function
      2. Returning a Value
      3. Returning an Array
    2. JavaScript Objects
      1. Declaring a Class
      2. Creating an Object
      3. Accessing Objects
      4. The prototype Keyword
    3. JavaScript Arrays
      1. Numeric Arrays
      2. Associative Arrays
      3. Multidimensional Arrays
      4. Using Array Methods
    4. Test Your Knowledge
  19. 16. JavaScript and PHP Validation and Error Handling
    1. Validating User Input with JavaScript
      1. The validate.html Document (Part One)
      2. The validate.html Document (Part Two)
    2. Regular Expressions
      1. Matching Through Metacharacters
      2. Fuzzy Character Matching
      3. Grouping Through Parentheses
      4. Character Classes
      5. Some More Complicated Examples
      6. Summary of Metacharacters
      7. General Modifiers
      8. Using Regular Expressions in JavaScript
      9. Using Regular Expressions in PHP
    3. Redisplaying a Form After PHP Validation
    4. Test Your Knowledge
  20. 17. Using Ajax
    1. What Is Ajax?
    2. Using XMLHttpRequest
    3. Implementing Ajax via POST Requests
      1. The readyState Property
      2. The Server Half of the Ajax Process
    4. Using GET Instead of POST
    5. Sending XML Requests
      1. About XML
      2. Why Use XML?
    6. Using Frameworks for Ajax
    7. Test Your Knowledge
  21. 18. Introduction to CSS
    1. Importing a Style Sheet
      1. Importing a Style Sheet from Within HTML
    2. Embedded Style Settings
      1. Using IDs
      2. Using Classes
    3. CSS Rules
      1. Using Semicolons
      2. Multiple Assignments
      3. Using Comments
    4. Style Types
      1. Default Styles
      2. User Styles
      3. External Style Sheets
      4. Internal Styles
      5. Inline Styles
    5. CSS Selectors
      1. The Type Selector
      2. The Descendant Selector
      3. The Child Selector
      4. The Adjacent Sibling Selector
      5. The ID Selector
      6. The Class Selector
      7. The Attribute Selector
      8. The Universal Selector
      9. Selecting by Group
    6. The CSS Cascade
      1. Style Sheet Creators
      2. Style Sheet Methods
      3. Style Sheet Selectors
    7. The Difference Between <div> and <span>
    8. Measurements
    9. Fonts and Typography
      1. font-family
      2. font-style
      3. font-size
      4. font-weight
    10. Managing Text Styles
      1. Decoration
      2. Spacing
      3. Alignment
      4. Transformation
      5. Indenting
    11. CSS Colors
      1. Short Color Strings
      2. Gradients
    12. Positioning Elements
      1. Absolute Positioning
      2. Relative Positioning
      3. Fixed Positioning
      4. Comparing Positioning Types
    13. Pseudoclasses
    14. Pseudoelements
    15. Shorthand Rules
    16. The Box Model and Layout
      1. Setting Margins
      2. Applying Borders
      3. Adjusting Padding
      4. Object Contents
    17. Test Your Knowledge
  22. 19. Advanced CSS with CSS3
    1. Attribute Selectors
      1. Matching Parts of Strings
    2. The box-sizing Property
    3. CSS3 Backgrounds
      1. The background-clip Property
      2. The background-origin Property
      3. The background-size Property
      4. Multiple Backgrounds
    4. CSS3 Borders
      1. The border-color Property
      2. The border-radius Property
    5. Box Shadows
    6. Element Overflow
    7. Multicolumn Layout
    8. Colors and Opacity
      1. HSL Colors
      2. HSLA Colors
      3. RGB Colors
      4. RGBA Colors
      5. The opacity Property
    9. Text Effects
      1. The text-shadow Property
      2. The text-overflow Property
      3. The word-wrap Property
    10. Web Fonts
      1. Google Web Fonts
    11. Transformations
    12. Transitions
      1. Properties to Transition
      2. Transition Duration
      3. Transition Delay
      4. Transition Timing
      5. Shorthand Syntax
    13. Test Your Knowledge
  23. 20. Accessing CSS from JavaScript
    1. Revisiting the getElementById Function
      1. The O Function
      2. The S Function
      3. The C Function
      4. Including the Functions
    2. Accessing CSS Properties from JavaScript
      1. Some Common Properties
      2. Other Properties
    3. Inline JavaScript
      1. The this Keyword
      2. Attaching Events to Objects in a Script
      3. Attaching to Other Events
    4. Adding New Elements
      1. Removing Elements
      2. Alternatives to Adding and Removing Elements
    5. Using Interrupts
      1. Using setTimeout
      2. Canceling a Timeout
      3. Using setInterval
      4. Using Interrupts for Animation
    6. Test Your Knowledge
  24. 21. Bringing It All Together
    1. Designing a Social Networking Site
    2. On the Website
    3. functions.php
      1. The Functions
    4. header.php
    5. setup.php
    6. index.php
    7. signup.php
      1. Checking for Username Availability
    8. checkuser.php
    9. login.php
    10. profile.php
      1. Adding the “About Me” Text
      2. Adding a Profile Image
      3. Processing the Image
      4. Displaying the Current Profile
    11. members.php
      1. Viewing a User’s Profile
      2. Adding and Dropping Friends
      3. Listing All Members
    12. friends.php
    13. messages.php
    14. logout.php
    15. styles.css
  25. A. Solutions to the Chapter Questions
    1. Chapter 1 Answers
    2. Chapter 2 Answers
    3. Chapter 3 Answers
    4. Chapter 4 Answers
    5. Chapter 5 Answers
    6. Chapter 6 Answers
    7. Chapter 7 Answers
    8. Chapter 8 Answers
    9. Chapter 9 Answers
    10. Chapter 10 Answers
    11. Chapter 11 Answers
    12. Chapter 12 Answers
    13. Chapter 13 Answers
    14. Chapter 14 Answers
    15. Chapter 15 Answers
    16. Chapter 16 Answers
    17. Chapter 17 Answers
    18. Chapter 18 Answers
    19. Chapter 19 Answers
    20. Chapter 20 Answers
  26. B. Online Resources
    1. PHP Resource Sites
    2. MySQL Resource Sites
    3. JavaScript Resource Sites
    4. Ajax Resource Sites
    5. Miscellaneous Resource Sites
    6. O’Reilly Resource Sites
  27. C. MySQL’s FULLTEXT Stopwords
  28. D. MySQL Functions
    1. String Functions
      1. CONCAT()
      2. CONCAT_WS()
      3. LEFT()
      4. RIGHT()
      5. MID()
      6. LENGTH()
      7. LPAD()
      8. RPAD
      9. LOCATE()
      10. LOWER()
      11. UPPER()
      12. QUOTE()
      13. REPEAT()
      14. REPLACE()
      15. TRIM()
      16. LTRIM() and RTRIM()
    2. Date Functions
      1. CURDATE()
      2. DATE()
      3. DATE_ADD()
      4. DATE_FORMAT()
      5. DAY()
      6. DAYNAME()
      7. DAYOFWEEK()
      8. DAYOFYEAR()
      9. LAST_DAY()
      10. MAKEDATE()
      11. MONTH()
      12. MONTHNAME()
      13. SYSDATE()
      14. YEAR()
      15. WEEK()
      16. WEEKDAY()
    3. Time Functions
      1. CURTIME()
      2. HOUR()
      3. MINUTE()
      4. SECOND()
      5. MAKETIME()
      6. TIMEDIFF()
      7. UNIX_TIMESTAMP()
      8. FROM_UNIXTIME()
  29. Index
  30. About the Author
  31. Colophon
  32. Copyright
O'Reilly logo

Operators

PHP offers a lot of powerful operators, ranging from arithmetic, string, and logical operators to operators for assignment, comparison, and more (see Table 4-1).

Table 4-1. PHP operator types

Operator

Used for

Example

Arithmetic

Basic mathematics

$a + $b

Array

Array union

$a + $b

Assignment

Assigning values

$a = $b + 23

Bitwise

Manipulating bits within bytes

12 ^ 9

Comparison

Comparing two values

$a < $b

Execution

Executing contents of backticks

`ls -al`

Increment/Decrement

Adding or subtracting 1

$a++

Logical

Boolean comparisons

$a and $b

String

Concatenation

$a . $b

Different types of operators take a different number of operands:

  • Unary operators, such as incrementing ($a++) or negation (-$a), take a single operand.

  • Binary operators, which represent the bulk of PHP operators (including addition, subtraction, multiplication, and division), take two operands.

  • There is one ternary operator, which takes the form x ? y : z. It’s a terse, single-line if statement that chooses between two expressions, depending on the result of a third one. This conditional operator takes three operands.

Operator Precedence

If all operators had the same precedence, they would be processed in the order in which they are encountered. In fact, many operators do have the same precedence—Example 4-5 illustrates one such case.

Example 4-5. Three equivalent expressions

1 + 2 + 3 - 4 + 5
2 - 4 + 5 + 3 + 1
5 + 2 - 4 + 1 + 3

Here you will see that although the numbers (and their preceding operators) have been moved around, the result of each expression is the value 7, because the plus and minus operators have the same precedence. We can try the same thing with multiplication and division (see Example 4-6).

Example 4-6. Three expressions that are also equivalent

1 * 2 * 3 / 4 * 5
2 / 4 * 5 * 3 * 1
5 * 2 / 4 * 1 * 3

Here the resulting value is always 7.5. But things change when we mix operators with different precedences in an expression, as in Example 4-7.

Example 4-7. Three expressions using operators of mixed precedence

1 + 2 * 3 - 4 * 5
2 - 4 * 5 * 3 + 1
5 + 2 - 4 + 1 * 3

If there were no operator precedence, these three expressions would evaluate to 25, −29, and 12, respectively. But because multiplication and division take precedence over addition and subtraction, there are implied parentheses around these parts of the expressions, which would look like Example 4-8 if they were visible.

Example 4-8. Three expressions showing implied parentheses

1 + (2 * 3) - (4 * 5)
2 - (4 * 5 * 3) + 1
5 + 2 - 4 + (1 * 3)

Clearly, PHP must evaluate the subexpressions within parentheses first to derive the semi-completed expressions in Example 4-9.

Example 4-9. After evaluating the subexpressions in parentheses

1 + (6) - (20)
2 - (60) + 1
5 + 2 - 4 + (3)

The final results of these expressions are −13, −57, and 6, respectively (quite different from the results of 25, −29, and 12 that we would have seen had there been no operator precedence).

Of course, you can override the default operator precedence by inserting your own parentheses and force the original results that we would have seen, had there been no operator precedence (see Example 4-10).

Example 4-10. Forcing left-to-right evaluation

((1 + 2) * 3 - 4) * 5
(2 - 4) * 5 * 3 + 1
(5 + 2 - 4 + 1) * 3

With parentheses correctly inserted, we now see the values 25, −29, and 12, respectively.

Table 4-2 lists PHP’s operators in order of precedence from high to low.

Table 4-2. The precedence of PHP operators (high to low)

Operator(s)

Type

()

Parentheses

++ −−

Increment/Decrement

!

Logical

* / %

Arithmetic

+ - .

Arithmetic and string

<< >>

Bitwise

< <= > >= <>

Comparison

== != === !==

Comparison

&

Bitwise (and references)

^

Bitwise

|

Bitwise

&&

Logical

||

Logical

? :

Ternary

= += -= *= /= .= %= &= != ^= <<= >>=

Assignment

and

Logical

xor

Logical

or

Logical

Associativity

We’ve been looking at processing expressions from left to right, except where operator precedence is in effect. But some operators can also require processing from right to left. The direction of processing is called the operator’s associativity.

This associativity becomes important in cases in which you do not explicitly force precedence. Table 4-3 lists all the operators that have right-to-left associativity.

Table 4-3. Operators with right-to-left associativity

Operator

Description

NEW

Create a new object

!

Logical NOT

~

Bitwise NOT

++ −−

Increment and decrement

+ −

Unary plus and negation

(int)

Cast to an integer

(double)

Cast to a float

(string)

Cast to a string

(array)

Cast to an array

(object)

Cast to an object

@

Inhibit error reporting

=

Assignment

For example, let’s take a look at the assignment operator in Example 4-11, where three variables are all set to the value 0.

Example 4-11. A multiple-assignment statement

<?php
$level = $score = $time = 0;
?>

This multiple assignment is possible only if the rightmost part of the expression is evaluated first and then processing continues in a right-to-left direction.

Note

As a PHP beginner, you should learn to avoid the potential pitfalls of operator associativity by always nesting your subexpressions within parentheses to force the order of evaluation. This will also help other programmers who may have to maintain your code to understand what is happening.

Relational Operators

Relational operators test two operands and return a Boolean result of either TRUE or FALSE. There are three types of relational operators: equality, comparison, and logical operators.

Equality operators

The equality operator, which we’ve already encountered a few times in this chapter, is == (two equals signs). It is important not to confuse it with the = (single equals sign) assignment operator. In Example 4-12, the first statement assigns a value and the second tests it for equality.

Example 4-12. Assigning a value and testing for equality

<?php
$month = "March";
if ($month == "March") echo "It's springtime";
?>

As you see, returning either TRUE or FALSE, the equality operator enables you to test for conditions using, for example, an if statement. But that’s not the whole story, because PHP is a loosely typed language. If the two operands of an equality expression are of different types, PHP will convert them to whatever type makes best sense to it.

For example, any strings composed entirely of numbers will be converted to numbers whenever compared with a number. In Example 4-13, $a and $b are two different strings and we would therefore expect neither of the if statements to output a result.

Example 4-13. The equality and identity operators

<?php
$a = "1000";
$b = "+1000";
if ($a == $b) echo "1";
if ($a === $b) echo "2";
?>

However, if you run the example, you will see that it outputs the number 1, which means that the first if statement evaluated to TRUE. This is because both strings were first converted to numbers, and 1000 is the same numerical value as +1000.

In contrast, the second if statement uses the identity operator—three equals signs in a row—which prevents PHP from automatically converting types. $a and $b are therefore compared as strings and are now found to be different, so nothing is output.

As with forcing operator precedence, whenever you feel there may be doubt about how PHP will convert operand types, you can use the identity operator to turn off this behavior.

In the same way that you can use the equality operator to test for operands being equal, you can test for them not being equal using !=, the inequality operator. Take a look at Example 4-14, which is a rewrite of Example 4-13 in which the equality and identity operators have been replaced with their inverses.

Example 4-14. The inequality and not identical operators

<?php
$a = "1000";
$b = "+1000";
if ($a != $b) echo "1";
if ($a !== $b) echo "2";
?>

As you might expect, the first if statement does not output the number 1, because the code is asking whether $a and $b are not equal to each other numerically.

Instead, it outputs the number 2, because the second if statement is asking whether $a and $b are not identical to each other in their present operand types, and the answer is TRUE; they are not the same.

Comparison operators

Using comparison operators, you can test for more than just equality and inequality. PHP also gives you > (is greater than), < (is less than), >= (is greater than or equal to), and <= (is less than or equal to) to play with. Example 4-15 shows these operators in use.

Example 4-15. The four comparison operators

<?php
$a = 2; $b = 3;
if ($a > $b)  echo "$a is greater than $b<br />";
if ($a < $b)  echo "$a is less than $b<br />";
if ($a >= $b) echo "$a is greater than or equal to $b<br />";
if ($a <= $b) echo "$a is less than or equal to $b<br />";
?>

In this example, where $a is 2 and $b is 3, the following is output:

2 is less than 3
2 is less than or equal to 3

Try this example yourself, altering the values of $a and $b, to see the results. Try setting them to the same value and see what happens.

Logical operators

Logical operators produce true-or-false results, and therefore are also known as Boolean operators. There are four of them (see Table 4-4).

Table 4-4. The logical operators

Logical operator

Description

AND

TRUE if both operands are TRUE

OR

TRUE if either operand is TRUE

XOR

TRUE if one of the two operands is TRUE

NOT

TRUE if the operand is FALSE or FALSE if the operand is TRUE

You can see these operators used in Example 4-16. Note that the ! symbol is required by PHP in place of the word NOT. Furthermore, the operators can be lower- or uppercase.

Example 4-16. The logical operators in use

<?php
$a = 1; $b = 0;
echo ($a AND $b) . "<br />";
echo ($a or $b)  . "<br />";
echo ($a XOR $b) . "<br />";
echo !$a         . "<br />";
?>

This example outputs NULL, 1, 1, NULL, meaning that only the second and third echo statements evaluate as TRUE. (Remember that NULL—or nothing—represents a value of FALSE.) This is because the AND statement requires both operands to be TRUE if it is going to return a value of TRUE, while the fourth statement performs a NOT on the value of $a, turning it from TRUE (a value of 1) to FALSE. If you wish to experiment with this, try out the code, giving $a and $b varying values of 1 and 0.

Note

When coding, remember to bear in mind that AND and OR have lower precedence than the other versions of the operators, && and ||. In complex expressions, it may be safer to use && and || for this reason.

The OR operator can cause unintentional problems in if statements, because the second operand will not be evaluated if the first is evaluated as TRUE. In Example 4-17, the function getnext will never be called if $finished has a value of 1.

Example 4-17. A statement using the OR operator

<?php
if ($finished == 1 OR getnext() == 1) exit;
?>

If you need getnext to be called at each if statement, you could rewrite the code as has been done in Example 4-18.

Example 4-18. The if…OR statement modified to ensure calling of getnext

<?php
$gn = getnext();
if ($finished == 1 OR $gn == 1) exit;
?>

In this case, the code in function getnext will be executed and the value returned stored in $gn before the if statement.

Note

Another solution is to simply switch the two clauses to make sure that getnext is executed, as it will then appear first in the expression.

Table 4-5 shows all the possible variations of using the logical operators. You should also note that !TRUE equals FALSE and !FALSE equals TRUE.

Table 4-5. All possible PHP logical expressions

Inputs

Operators and results

a

b

AND

OR

XOR

TRUE

TRUE

TRUE

TRUE

FALSE

TRUE

FALSE

FALSE

TRUE

TRUE

FALSE

TRUE

FALSE

TRUE

TRUE

FALSE

FALSE

FALSE

FALSE

FALSE

The best content for your career. Discover unlimited learning on demand for around $1/day.