PHP Tutorials - Herong's Tutorial Notes
Dr. Herong Yang, Version 2.21

Operations and Expressions

PHP Tutorials - Herong's Tutorial Notes © Dr. Herong Yang

Non ASCII Characters with MySQL

Inputting Non ASCII Characters

Controlling Response Header Lines

HTTP Request Variables

Sessions

Using Cookies

PHP SOAP Extension

PHP SOAP Extension - Server

Directories, Files and Images

Using MySQL with PHP

... Table of Contents

This chapter describes:

  • What are PHP operations.
  • How expression works in PHP.

Operations

PHP supports most types of operations used in other languages:

  • Bitwise Operations: and, or, xor, not, shift left, and shift right.
  • Incrementing/Decrementing Operations: pre-inrement, post-increment, pre-decrement, and post-decrement.
  • Arithmetic Operations: negation, addition, subtraction, multiplication, division, and modulus.
  • Comparison Operations: equal, identical, not equal, not identical, less than, greater than, less than or equal, and greater than or equal to.
  • Logical Operations: and, or, xor, and not.
  • String Operations: concatenation.

Note that "identical" and "not identical" operations are not commonly used in other languages.

Expressions

PHP supports most common rules on building expressions in other languages. It also supports some special rules:

  • The data type of the resulting value of an expression does not match the data type required by the evaluation context, the resulting value will be automatically converted the required data type.
  • Like Perl, 0 and no-value will be converted to false in a boolean context. Other values will be converted to true in a boolean context.
  • Assignment is also an expression. The resulting value of an assignment is the value used in the assignment.

To show you some of the features, I wrote the following sample PHP script, ExpressTest.php:

<?php # ExpressionTest.php
# Copyright (c) 2002 by Dr. Herong Yang, http://www.herongyang.com/
# 
   print "\nSimple expressions:\n";
   $a = 1 + 2 * 3 / 4; # Expression with arithmetic operations
   print "   a = $a\n";
   $b = 'A' + 1; # Context requires 'A' to be evaluated to a float
   print "   b = $b\n";
   $c = 'A' . 1; # Context requires 1 to be evaluated to a string
   print "   c = $c\n";
   $d = true && 9; # Context requires 9 to be evaluated to true
   print "   d = $d\n";
#
   print "\nSpecial expressions:\n";
   $a = $b = "Apple"; # Using assignement as an expression
   print "   a = $a\n";
   $x = $a === $b;
   print "   x = $x\n";
?>

Here is the output:

Simple expressions:
   a = 2.5
   b = 1
   c = A1
   d = 1

Special expressions:
   a = Apple
   x = 1
Dr. Herong Yang, updated in 2006
PHP Tutorials - Herong's Tutorial Notes - Operations and Expressions