Home > Articles

PHP Crash Course

This chapter is from the book

Using Operators

Operators are symbols that you can use to manipulate values and variables by performing an operation on them. You need to use some of these operators to work out the totals and tax on the customer’s order.

We’ve already mentioned two operators: the assignment operator (=) and the string concatenation operator (.). In the following sections, we describe the complete list.

In general, operators can take one, two, or three arguments, with the majority taking two. For example, the assignment operator takes two: the storage location on the left side of the = symbol and an expression on the right side. These arguments are called operands—that is, the things that are being operated upon.

Arithmetic Operators

Arithmetic operators are straightforward; they are just the normal mathematical operators. PHP’s arithmetic operators are shown in Table 1.1.

Table 1.1 PHP’s Arithmetic Operators

Operator

Name

Example

+

Addition

$a + $b

-

Subtraction

$a - $b

*

Multiplication

$a * $b

/

Division

$a / $b

%

Modulus

$a % $b

With each of these operators, you can store the result of the operation, as in this example:

$result = $a + $b;

Addition and subtraction work as you would expect. The result of these operators is to add or subtract, respectively, the values stored in the $a and $b variables.

You can also use the subtraction symbol (-) as a unary operator—that is, an operator that takes one argument or operand—to indicate negative numbers, as in this example:

$a = -1;

Multiplication and division also work much as you would expect. Note the use of the asterisk as the multiplication operator rather than the regular multiplication symbol, and the forward slash as the division operator rather than the regular division symbol.

The modulus operator returns the remainder calculated by dividing the $a variable by the $b variable. Consider this code fragment:

$a = 27;
$b = 10;
$result = $a%$b;

The value stored in the $result variable is the remainder when you divide 27 by 10—that is, 7.

You should note that arithmetic operators are usually applied to integers or doubles. If you apply them to strings, PHP will try to convert the string to a number. If it contains an e or an E, it will be read as being in scientific notation and converted to a float; otherwise, it will be converted to an integer. PHP will look for digits at the start of the string and use them as the value; if there are none, the value of the string will be zero.

String Operators

You’ve already seen and used the only string operator. You can use the string concatenation operator to add two strings and to generate and store a result much as you would use the addition operator to add two numbers:

$a = "Bob's ";
$b = "Auto Parts";
$result = $a.$b;

The $result variable now contains the string "Bob's Auto Parts".

Assignment Operators

You’ve already seen the basic assignment operator (=). Always refer to this as the assignment operator and read it as “is set to.” For example,

$totalqty = 0;

This line should be read as “$totalqty is set to zero.” We explain why when we discuss the comparison operators later in this chapter, but if you call it equals, you will get confused.

Values Returned from Assignment

Using the assignment operator returns an overall value similar to other operators. If you write

$a + $b

the value of this expression is the result of adding the $a and $b variables together. Similarly, you can write

$a = 0;

The value of this whole expression is zero.

This technique enables you to form expressions such as

$b = 6 + ($a = 5);

This line sets the value of the $b variable to 11. This behavior is generally true of assignments: The value of the whole assignment statement is the value that is assigned to the left operand.

When working out the value of an expression, you can use parentheses to increase the precedence of a subexpression, as shown here. This technique works exactly the same way as in mathematics.

Combined Assignment Operators

In addition to the simple assignment, there is a set of combined assignment operators. Each of them is a shorthand way of performing another operation on a variable and assigning the result back to that variable. For example,

$a += 5;

This is equivalent to writing

$a = $a + 5;

Combined assignment operators exist for each of the arithmetic operators and for the string concatenation operator. A summary of all the combined assignment operators and their effects is shown in Table 1.2.

Table 1.2 PHP’s Combined Assignment Operators

Operator

Use

Equivalent To

+=

$a += $b

$a = $a + $b

-=

$a -= $b

$a = $a - $b

*=

$a *= $b

$a = $a * $b

/=

$a /= $b

$a = $a / $b

%=

$a %= $b

$a = $a % $b

.=

$a .= $b

$a = $a . $b

Pre- and Post-Increment and Decrement

The pre- and post-increment (++) and decrement (--) operators are similar to the += and -= operators, but with a couple of twists.

All the increment operators have two effects: They increment and assign a value. Consider the following:

$a=4;
echo ++$a;

The second line uses the pre-increment operator, so called because the ++ appears before the $a. This has the effect of first incrementing $a by 1 and second, returning the incremented value. In this case, $a is incremented to 5, and then the value 5 is returned and printed. The value of this whole expression is 5. (Notice that the actual value stored in $a is changed: It is not just returning $a + 1.)

If the ++ is after the $a, however, you are using the post-increment operator. It has a different effect. Consider the following:

$a=4;
echo $a++;

In this case, the effects are reversed. That is, first, the value of $a is returned and printed, and second, it is incremented. The value of this whole expression is 4. This is the value that will be printed. However, the value of $a after this statement is executed is 5.

As you can probably guess, the behavior is similar for the -- (decrement) operator. However, the value of $a is decremented instead of being incremented.

Reference Operator

The reference operator (&, an ampersand) can be used in conjunction with assignment. Normally, when one variable is assigned to another, a copy is made of the first variable and stored elsewhere in memory. For example,

$a = 5;
$b = $a;

These code lines make a second copy of the value in $a and store it in $b. If you subsequently change the value of $a, $b will not change:

$a = 7; // $b will still be 5

You can avoid making a copy by using the reference operator. For example,

$a = 5;
$b = &$a;
$a = 7; // $a and $b are now both 7

References can be a bit tricky. Remember that a reference is like an alias rather than like a pointer. Both $a and $b point to the same piece of memory. You can change this by unsetting one of them as follows:

unset($a);

Unsetting does not change the value of $b (7) but does break the link between $a and the value 7 stored in memory.

Comparison Operators

The comparison operators compare two values. Expressions using these operators return either of the logical values true or false depending on the result of the comparison.

The Equal Operator

The equal comparison operator (==, two equal signs) enables you to test whether two values are equal. For example, you might use the expression

$a == $b

to test whether the values stored in $a and $b are the same. The result returned by this expression is true if they are equal or false if they are not.

You might easily confuse == with =, the assignment operator. Using the wrong operator will work without giving an error but generally will not give you the result you wanted. In general, nonzero values evaluate to true and zero values to false. Say that you have initialized two variables as follows:

$a = 5;
$b = 7;

If you then test $a = $b, the result will be true. Why? The value of $a = $b is the value assigned to the left side, which in this case is 7. Because 7 is a nonzero value, the expression evaluates to true. If you intended to test $a == $b, which evaluates to false, you have introduced a logic error in your code that can be extremely difficult to find. Always check your use of these two operators and check that you have used the one you intended to use.

Using the assignment operator rather than the equals comparison operator is an easy mistake to make, and you will probably make it many times in your programming career.

Other Comparison Operators

PHP also supports a number of other comparison operators. A summary of all the comparison operators is shown in Table 1.3. One to note is the identical operator (===), which returns true only if the two operands are both equal and of the same type. For example, 0=='0' will be true, but 0==='0' will not because one zero is an integer and the other zero is a string.

Table 1.3 PHP’s Comparison Operators

Operator

Name

Use

==

Equals

$a == $b

===

Identical

$a === $b

!=

Not equal

$a != $b

!==

Not identical

$a !== $b

<>

Not equal (comparison operator)

$a <> $b

<<

Less than

$a < $b

></p>

Greater than (comparison operator)

$a > $b

<=

Less than or equal to

$a <= $b

>=

Greater than or equal to

$a >= $b

Logical Operators

The logical operators combine the results of logical conditions. For example, you might be interested in a case in which the value of a variable, $a, is between 0 and 100. You would need to test both the conditions $a >= 0 and $a <= 100, using the AND operator, as follows:

$a >= 0 && $a <=100

PHP supports logical AND, OR, XOR (exclusive or), and NOT.

The set of logical operators and their use is summarized in Table 1.4.

Table 1.4 PHP’s Logical Operators

Operator

Name

Use

Result

!

NOT

!$b

Returns true if $b is false and vice versa

&&

AND

$a && $b

Returns true if both $a and $b are true; otherwise false

||

OR

$a || $b

Returns true if either $a or $b or both are true; otherwise false

and

AND

$a and $b

Same as &&, but with lower precedence

or

OR

$a or $b

Same as ||, but with lower precedence

xor

XOR

$a x or $b

Returns true if either $a or $b is true, and false if they are both true or both false.

The and and or operators have lower precedence than the && and || operators. We cover precedence in more detail later in this chapter.

Bitwise Operators

The bitwise operators enable you to treat an integer as the series of bits used to represent it. You probably will not find a lot of use for the bitwise operators in PHP, but a summary is shown in Table 1.5.

Table 1.5 PHP’s Bitwise Operators

Operator

Name

Use

Result

&

Bitwise AND

$a & $b

Bits set in $a and $b are set in the result.

|

Bitwise OR

$a | $b

Bits set in $a or $b are set in the result.

~

Bitwise NOT

~$a

Bits set in $a are not set in the result and vice versa.

^

Bitwise XOR

$a ^ $b

Bits set in $a or $b but not in both are set in the result.

<<

Left shift

$a << $b

Shifts $a left $b bits.

>>

Right shift

$a >> $b

Shifts $a right $b bits.

Other Operators

In addition to the operators we have covered so far, you can use several others.

The comma operator (,) separates function arguments and other lists of items. It is normally used incidentally.

Two special operators, new and ->, are used to instantiate a class and access class members, respectively. They are covered in detail in Chapter 6.

There are a few others that we discuss briefly here.

The Ternary Operator

The ternary operator (?:) takes the following form:

condition ? value if true : value if false

This operator is similar to the expression version of an if-else statement, which is covered later in this chapter.

A simple example is

($grade >= 50 ? 'Passed' : 'Failed')

This expression evaluates student grades to 'Passed' or 'Failed'.

The Error Suppression Operator

The error suppression operator (@) can be used in front of any expression—that is, anything that generates or has a value. For example,

$a = @(57/0);

Without the @ operator, this line generates a divide-by-zero warning. With the operator included, the error is suppressed.

If you are suppressing warnings in this way, you need to write some error handling code to check when a warning has occurred. If you have PHP set up with the track_errors feature enabled in php.ini, the error message will be stored in the global variable $php_errormsg.

The Execution Operator

The execution operator is really a pair of operators—a pair of backticks (``) in fact. The backtick is not a single quotation mark; it is usually located on the same key as the ~ (tilde) symbol on your keyboard.

PHP attempts to execute whatever is contained between the backticks as a command at the server’s command line. The value of the expression is the output of the command.

For example, under Unix-like operating systems, you can use

$out = `ls -la`;
echo '<pre>'.$out.'</pre>';

Or, equivalently on a Windows server, you can use

$out = `dir c:`;
echo '<pre>'.$out.'</pre>';

Either version obtains a directory listing and stores it in $out. It can then be echoed to the browser or dealt with in any other way.

There are other ways of executing commands on the server. We cover them in Chapter 17, “Interacting with the File System and the Server.”

Array Operators

There are a number of array operators. The array element operators ([]) enable you to access array elements. You can also use the => operator in some array contexts. These operators are covered in Chapter 3.

You also have access to a number of other array operators. We cover them in detail in Chapter 3 as well, but we included them here in Table 1.6 for completeness.

Table 1.6 PHP’s Array Operators

Operator

Name

Use

Result

+

Union

$a + $b

Returns an array containing everything in $a and $b

==

Equality

$a == $b

Returns true if $a and $b have the same key and value pairs

===

Identity

$a === $b

Returns true if $a and $b have the same key and value pairs in the same order and of the same type.

!=

Inequality

$a != $b

Returns true if $a and $b are not equal

<>

Inequality

$a <> $b

Returns true if $a and $b are not equal

!==

Non-identity

$a !== $b

Returns true if $a and $b are not identical

You will notice that the array operators in Table 1.6 all have equivalent operators that work on scalar variables. As long as you remember that + performs addition on scalar types and union on arrays—even if you have no interest in the set arithmetic behind that behavior—the behaviors should make sense. You cannot usefully compare arrays to scalar types.

The Type Operator

There is one type operator: instanceof. This operator is used in object-oriented programming, but we mention it here for completeness. (Object-oriented programming is covered in Chapter 6.)

The instanceof operator allows you to check whether an object is an instance of a particular class, as in this example:

class sampleClass{};
$myObject = new sampleClass();
if ($myObject instanceof sampleClass)
  echo  "myObject is an instance of sampleClass";

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020