166 views

Chapter 3..PHP Basics (Part-4)

Constants

A constant is a value that cannot be modified throughout the execution of a program. Constants are particularly useful when working with values that definitely will not require modification, such as pi (3.141592) or the number of feet in a mile (5,280). Once a constant has been defined, it cannot be changed (or redefined) at any other point of the program. Constants are defined using the define() function.

Defining a Constant
The define() function defines a constant by assigning a value to a name. Its prototype follows:
boolean define(string name, mixed value [, bool case_insensitive])

If the optional parameter case_insensitive is included and assigned TRUE, subsequent references to the constant will be case insensitive. Consider the following example in which the mathematical constant PI is defined:

                  define("PI", 3.141592);

The constant is subsequently used in the following listing:

                printf("The value of pi is %f", PI);
                $pi2 = 2 * PI;
                printf("Pi doubled equals %f", $pi2);

This code produces the following results:

                The value of pi is 3.141592.
                Pi doubled equals 6.283184.

There are several points to note regarding the previous listing. The first is that constant references are not prefaced with a dollar sign. The second is that you can’t redefine or undefine the constant once it has been defined (e.g., 2*PI); if you need to produce a value based on the constant, the value must be stored in another variable. Finally, constants are global; they can be referenced anywhere in your script.

Expressions

An expression is a phrase representing a particular action in a program. All expressions consist of at least one operand and one or more operators. A few examples follow:

               $a = 5; // assign integer value 5 to the variable $a
               $a = "5"; // assign string value "5" to the variable $a
               $sum = 50 + $some_int; // assign sum of 50 + $some_int to $sum
                $wine = "Zinfandel"; // assign "Zinfandel" to the variable $wine
                $inventory++; // increment the variable $inventory by 1



Operands
Operands are the inputs of an expression. You might already be familiar with the manipulation and use of operands not only through everyday mathematical calculations, but also through prior programming experience. Some examples of operands follow:

                   $a++; // $a is the operand
                   $sum = $val1 + val2; // $sum, $val1 and $val2 are operands


Operators

An operator is a symbol that specifies a particular action in an expression. Many operators may be familiar to you. Regardless, you should remember that PHP’s automatic type conversion will convert types based on the type of operator placed between the two operands, which is not always the case in other programming languages.
The precedence and associativity of operators are significant characteristics of a programming language. Both concepts are introduced in this section. Table 3-4
contains a complete listing of all operators, ordered from highest to lowest precedence.
Table 3-4. Operator Precedence, Associativity, and Purpose

——————————————————————————————————-

      Operator         Associativity      Purpose
-------------------------------------------------------------------------------------------------------
      new                NA            Object instantiation
     ( )                 NA            Expression subgrouping
     [ ]                 Right         Index enclosure
     ! ~ ++ --           Right         Boolean NOT, bitwise NOT, increment,
                                           decrement
     @                   Right        Error suppression
     / * %               Left          Division, multiplication, modulus
     + - .               Left          Addition, subtraction, concatenation
     << >>               Left          Shift left, shift right (bitwise)
     < <= > >=           NA            Less than, less than or equal to, greater than,
                                          greater than or equal to
     == != === <>         NA          Is equal to, is not equal to, is identical to, is
                                         not equal to
     & ^ |                Left        Bitwise AND, bitwise XOR, bitwise OR
     && ||                Left        Boolean AND, Boolean OR
     ?:                   Right       Ternary operator
     = += *= /= .= %=&=
    |= ^= <<= >>=         Right         Assignment operators
    AND XOR OR            Left          Boolean AND, Boolean XOR, Boolean OR
   ,                      Left          Expression separation; example: $days =
                                        array(1=>"Monday", 2=>"Tuesday")

———————————————————————————————————-

Operator Precedence
Operator precedence is a characteristic of operators that determines the order in which they evaluate the operands surrounding them. PHP follows the standard
precedence rules used in elementary school math class. Consider a few examples:

                  $total_cost = $cost + $cost * 0.06;

This is the same as writing

                  $total_cost = $cost + ($cost * 0.06);

because the multiplication operator has higher precedence than the addition operator.
Operator Associativity
The associativity characteristic of an operator specifies how operations of the same precedence (i.e., having the same precedence value, as displayed in Table 3-3) are evaluated as they are executed. Associativity can be performed in two directions, left to right or right to left. Left-to-right associativity means that the various operations making up the expression are evaluated from left to right. Consider the following example:

                  $value = 3 * 4 * 5 * 7 * 2;

The preceding example is the same as the following:

                   $value = ((((3 * 4) * 5) * 7) * 2);

This expression results in the value 840 because the multiplication (*) operator is left-to-right associative.
In contrast, right-to-left associativity evaluates operators of the same precedence from right to left:

                    $c = 5;
                    print $value = $a = $b = $c;

The preceding example is the same as the following:

                   $c = 5;
                   $value = ($a = ($b = $c));

When this expression is evaluated, variables $value, $a, $b, and $c will all contain the value 5 because the assignment operator (=) has right-to-left associativity.

Arithmetic Operators
The arithmetic operators, listed in Table 3-5, perform various mathematical operations and will probably be used frequently in many of your PHP programs.
Fortunately, they are easy to use.
Incidentally, PHP provides a vast assortment of predefined mathematical functions capable of performing base conversions and calculating logarithms, square
roots, geometric values, and more. Check the manual for an updated list of these functions.

—————————————————————————–

Example           Label                   Outcome
-------------------------------------------------------
$a + $b           Addition                Sum of $a and $b
$a - $b           Subtraction             Difference of $a and $b
$a * $b           Multiplication          Product of $a and $b
$a / $b           Division                Quotient of $a and $b
$a % $b           Modulus                 Remainder of $a divided by $b

——————————————————————————

Assignment Operators
The assignment operators assign a data value to a variable. The simplest form of assignment operator just assigns some value, while others (known as shortcut assignment operators) perform some other operation before making the assignment. Table 3-6 lists examples using this type of operator.

——————————————————————————

Example           Label                          Outcome
------------------------------------------------------------------------------
$a = 5        Assignment                        $a equals 5
$a += 5       Addition-assignment               $a equals $a plus 5
$a *= 5       Multiplication-assignment         $a equals $a multiplied by 5
$a /= 5       Division-assignment               $a equals $a divided by 5
$a .= 5       Concatenation-assignment          $a equals $a concatenated with 5

——————————————————————————-

String Operators
PHP’s string operators (see Table 3-7) provide a convenient way in which to concatenate strings together. There are two such operators, including the concatenation operator (.) and the concatenation assignment operator (.=) discussed in the previous section.

———————————————————————————-

Example            Label                      Outcome
----------------------------------------------------------
$a = "abc"."def";  Concatenation            $a is assigned the string abcdef
$a .= "ghijkl";    Concatenation-assignment $a equals its current value
                                            concatenated with “ghijkl”

———————————————————————————

Here is an example involving string operators:
// $a contains the string value “Spaghetti & Meatballs”;
$a = “Spaghetti” . “& Meatballs”;
$a .= ” are delicious.”
// $a contains the value “Spaghetti & Meatballs are delicious.”
The two concatenation operators are hardly the extent of PHP’s string-handling capabilities. Read Chapter 9 for a complete accounting of this important feature.

Increment and Decrement Operators

The increment (++) and decrement (–) operators listed in Table 3-8 present a minor  convenience in terms of code clarity, providing shortened means by which you can add 1 to or subtract 1 from the current value of a variable.
Table 3-8. Increment and Decrement Operators

————————————————————————————–

Example           Label           Outcome
-----------------------------------------------------------------
++$a, $a++       Increment        Increment $a by 1
--$a, $a--       Decrement        Decrement $a by 1

————————————————————————————–

These operators can be placed on either side of a variable, and the side on which they are placed provides a slightly different effect. Consider the outcomes of the
following examples:
$inv = 15; // Assign integer value 15 to $inv.
$oldInv = $inv–; // Assign $oldInv the value of $inv, then decrement $inv.
$origInv = ++$inv; // Increment $inv, then assign the new $inv value to $origInv.
As you can see, the order in which the increment and decrement operators are used has an important effect on the value of a variable. Prefixing the operand with one of these operators is known as a preincrement and predecrement operation, while postfixing the operand is known as a postincrement and postdecrement operation.

Logical Operators
Much like the arithmetic operators, logical operators (see Table 3-9) will probably play a major role in many of your PHP applications, providing a way to make decisions based on the values of multiple variables. Logical operators make it possible to direct the flow of a program and are used frequently with control structures, such as the if conditional and the while and for loops.
Logical operators are also commonly used to provide details about the outcome of other operations, particularly those that return a value:
file_exists(”filename.txt”) OR echo “File does not exist!”;
One of two outcomes will occur:
• The file filename.txt exists
• The sentence “File does not exist!” will be output
Table 3-9. Logical Operators

——————————————————————————–

Example          Label                          Outcome
--------------------------------------------------------------------------------
$a && $b         AND                      True if both $a and $b are true
$a AND $b        AND                      True if both $a and $b are true
$a || $b         OR                       True if either $a or $b is true
$a OR $b         OR                       True if either $a or $b is true
!$a              NOT                      True if $a is not true
NOT $a           NOT                      True if $a is not true
$a XOR $b        Exclusive OR             True if only $a or only $b is true

———————————————————————————-

Equality Operators

Equality operators (see Table 3-10) are used to compare two values, testing for equivalence.

———————————————————————————

Example           Label                            Outcome
----------------------------------------------------------
$a == $b         Is equal to             True if $a and $b are equivalent
$a != $b         Is not equal to         True if $a is not equal to $b
$a === $b        Is identical to         True if $a and $b are equivalent and $a and $b have
                                         the same type

———————————————————————————-

It is a common mistake for even experienced programmers to attempt to test for equality using just one equal sign (e.g., $a = $b). Keep in mind that this will result in the assignment of the contents of $b to $a and will not produce the expected results.

Comparison Operators
Comparison operators (see Table 3-11), like logical operators, provide a method to direct program flow through an examination of the comparative values of two or more variables.

————————————————————————————

Example       Label                              Outcome
------------------------------------------------------------
$a < $b       Less than                         True if $a is less than $b
$a > $b       Greater than                      True if $a is greater than $b
$a <= $b      Less than or equal to             True if $a is less than or equal to
                                                $b
$a >= $b      Greater than or equal to          True if $a is greater than or
                                                equal to $b
($a == 12) ? 5 : -1 Ternary                     If $a equals 12, return value is 5;
                                                otherwise, return value is –1

——————————————————————————————-

Note that the comparison operators should be used only for comparing numerical values. Although you may be tempted to compare strings with these operators, you will most likely not arrive at the expected outcome if you do so. There is a substantial set of predefined functions that compare string values, which are discussed in detail in Chapter 9.

Bitwise Operators
Bitwise operators examine and manipulate integer values on the level of individual bits that make up the integer value (thus the name). To fully understand this concept, you need at least an introductory knowledge of the binary representation of decimal integers. Table 3-12 presents a few decimal integers and their corresponding binary representations.

Binary Representations

————————————————————————————-

Decimal Integer                Binary Representation
2                              10
5                              101
10                             1010
12                             1100
145                            10010001
1,452,012                      101100010011111101100

——————————————————————————————

The bitwise operators listed in Table 3-13 are variations on some of the logical operators but can result in drastically different outcomes.

Bitwise Operators

--------------------------------------------------------------------------------------------
Example         Label                                   Outcome
--------------------------------------------------------------------------------------------
$a & $b         AND                          And together each bit contained in $a and $b
$a | $b         OR                           Or together each bit contained in $a and $b
$a ^ $b         XOR                          Exclusive-or together each bit contained in $a and $b
~ $b            NOT                           Negate each bit in $b
$a << $b        Shift left                    $a will receive the value of $b shifted left two bits
$a >> $b        Shift right                   $a will receive the value of $b shifted right two bits
-----------------------------------------------------------------------------------------------

If you are interested in learning more about binary encoding and bitwise operators and why they are important, check out Randall Hyde’s massive online reference, “The Art of Assembly Language Programming,” available at http://webster.cs.ucr.edu/.

One Trackback/Pingback

  1. INDEX - PHP & MySQL on Friday, March 6, 2009 at 6:54 pm

    [...] Chapter 3..PHP Basics(Part-4) (Constants,Expressions,Operators) Chapter 3..PHP Basics(Part-5) (String Interpolation, Double Quotes, Single Quotes, Heredoc) Chapter 3..PHP Basics(Part-6) (Control Structures, Conditional, if, else, elseif, switch Statement) Chapter 3..PHP Basics(Part-7) (Looping Statements, while, do…while, for, foreach, continue, break and goto Statements) Chapter 3..PHP Basics(Part-8) (File-Inclusion Statements, include(), require() Statement) « C# Day 1- Basics (part 7) Chapter 1.. Introducing PHP » Posted on Friday, February 6th, 2009 at 5:19 pm under INDEX | RSS 2.0 Feed Post Comment [...]

Post a Comment

You must be logged in to post a comment.