Home arrow PHP arrow Page 4 - The PHP Scripting Language

Expressions, Operators, and Variable Assignment - PHP

This article describes the basics of the PHP scripting language, which is very easy to learn if you are familiar with any programming language. It is excerpted from chapter two of the book Web Database Applications with PHP and MySQL, written by Hugh E. Williams and David Lane (O'Reilly, 2004; ISBN: 0596005431).

TABLE OF CONTENTS:
  1. The PHP Scripting Language
  2. Creating PHP scripts
  3. Character encoding
  4. Expressions, Operators, and Variable Assignment
  5. switch Statement
  6. Changing Loop Behavior
  7. Automatic Type Conversion
  8. User-Defined Functions
  9. Static variables
  10. Managing include files
By: O'Reilly Media
Rating: starstarstarstarstar / 32
September 29, 2005

print this article
SEARCH DEV SHED

TOOLS YOU CAN USE

advertisement

Weíve already described simple examples of assignment, in which a variable is assigned the value of an integer, string, or value of some other data type. The value on the right side of the equal sign is actually the simplest example of an expression.

An expression is anything that can be reduced to a single value, for example the sum1 + 2is an expression with an integer value of 3. Expressions can be complex combinations of operators and values, just as in mathematics. Examples of expressions (the first involving integers, the second involving integers and one floating point number) are:

6 + 3 -2
( 255.0 / 2 ) + 1

The basic syntax for expressions in PHP is taken from the C language and is familiar to someone who has worked in almost any high-level programming language. Here are some examples:

// Assign a value to a variable
$var = 1;
// Sum integers to produce an integer
$var = 4 + 7;
// Subtraction, multiplication, and division might have
// a result that is a float or an integer, depending on
// the initial value of $var
$var = (($var - 5) * 2) / 3;
// These all add 1 to $var
$var = $var + 1;
$var += 1;
$var++;
// And these all subtract 1 from $var
$var = $var - 1;
$var -= 1;
$var--;
// Double a value
$var = $var * 2;
$var *= 2;
// Halve a value
$var = $var / 2;
$var /= 2;
// These work with float types too
$var = 123.45 * 28.2;

There are many mathematical functions available in the math library of PHP for more complex tasks. We introduce some of these in the next chapter.

String expressions can be created using the dot-operator (.) to concatenate two strings:

// Assign a string value to a variable
$var = "test string";
// Concatenate two strings using the
// dot operator to produce "test string" $var = "test" . " string";
// Add a string to the end of another
// to produce "test string"
$var = "test";
$var = $var . " string";
// Here is a shortcut to add a string to
// the end of another
$var .= " test";

The following are all equivalent. The syntax you use is a matter of taste.

echo "test string";
echo "test " . "string";
echo "test ", "string";

The first contains a single string. The second contains an expression combining two strings, while the third contains two arguments to theechocommand.

The values returned from functions and many statements can be used as expressions including a variable assignment. In the following example, the assignment($x=42)is used as an integer expression with the value of 42:

// assign both $y and $x the value 42
$y = ($x = 42);

The parentheses are not needed in the example above; however, they highlight the fact that$x = 42is an expression.

PHP automatically converts types when combining values in an expression. For example, the expression4 + 7.0contains an integer and a float; in this case, PHP considers the integer as a floating-point number, and the result is of type float. The type conversions are largely straightforward; however, there are some traps, which are discussed later in this chapter.

Operator precedence

The term precedence in mathematics and programming refers to the decision concerning which operator is evaluated first. For instance, in the following expression, by convention, the multiplication operator is evaluated first, leading to a value of 32:

2 + 5 * 6

PHP defines the precedence of operators in an expression similar to how it is done in other languages. Multiplication and division occur before subtraction and addition, and so on. However, reliance on evaluation order leads to unreadable, confusing code. Rather than memorize the rules, we recommend you construct unambiguous expressions with parentheses, because parentheses have the highest precedence in evaluation.

For example, in the following fragment$variableis assigned a value of 32 because of the precedence of multiplication over addition:

$variable = 2 + 5 * 6;

But the result is much clearer if parentheses are used:

$variable = 2 + (5 * 6);

Conditions and Branches

Conditionals add control to scripts and permit choices. Different statements are executed depending on whether expressions are true or false. There are two branching statements in PHP: if, with the optionalelseclause, andswitch, usually with two or morecaseclauses.

if...else Statement

The if statement conditionally controls execution. The basic format of an if statement is to test whether a condition is trueand, if so, to execute one or more statements.

The followingifstatement executes theprintstatement and outputs the string when the conditional expression,$varis greater than 5, istrue:

if ($var > 5)
    print "The variable is greater than 5";


The expressions used in the examples in this section compare integers. They can be used to compare strings but usually not with the expected results. If strings need to be compared, use the PHP string library function strcmp( ). Itís discussed in more detail in Chapter 3.

Multiple statements can be executed as a block by encapsulating the statements within braces. If the expression evaluates astrue, the statements within the braces are executed. If the expression isníttrue, none of the statements are executed. Consider an example in which three statements are executed if the condition istrue:

if ($var > 5)
{
    print "The variable is greater than 5.";
   
// So, now let's set it to 5
    $var = 5;
    print "In fact, now it is equal to 5.";
}

Without the braces, anifstatement executes only the single, immediately following statement when the conditional expression evaluates totrue.

Theifstatement can have an optionalelseclause to execute a statement or block of statements if the expression evaluates asfalse. Consider an example:

if ($var > 5)
    print "Variable greater than 5";
else
    print "Variable less than or equal to 5";

Itís also common for theelseclause to execute a block of statements in braces, as in this example:

if ($var < 5)
{
    print "Variable is less than 5";
    print "-----------------------";
}
else
{
   
print "Variable is equal to or larger than 5";
    print "-------------------------------------";
}

Consecutive conditional tests can lead to examples such as:

if ($var < 5)
    print "Value is very small";
else
    if ($var < 10)
        print "Value is small";
    else
        if ($var < 20)
           
print "Value is normal";
       else
           if ($var < 30)
               print "Value is big";
           else
               print "Value is very big";

The indentation in the preceding example highlights the nested nature of the multiple tests. If consecutive, cascading tests are needed, theelseif statement can be used. The choice of which method to use is a matter of personal preference. This example has the same functionality as the previous example:

if ($var < 5)
   
print "Value is very small";
elseif ($var < 10)
   
print "Value is small";
elseif ($var < 20)
   
print "Value is normal";
elseif ($var < 30)
   
print "Value is big";
else
   
print "Value is very big";



 
 
>>> More PHP Articles          >>> More By O'Reilly Media
 

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort
   

PHP ARTICLES

- Hackers Compromise PHP Sites to Launch Attac...
- Red Hat, Zend Form OpenShift PaaS Alliance
- PHP IDE News
- BCD, Zend Extend PHP Partnership
- PHP FAQ Highlight
- PHP Creator Didn't Set Out to Create a Langu...
- PHP Trends Revealed in Zend Study
- PHP: Best Methods for Running Scheduled Jobs
- PHP Array Functions: array_change_key_case
- PHP array_combine Function
- PHP array_chunk Function
- PHP Closures as View Helpers: Lazy-Loading F...
- Using PHP Closures as View Helpers
- PHP File and Operating System Program Execut...
- PHP: Effects of Wrapping Code in Class Const...

Developer Shed Affiliates

 


Dev Shed Tutorial Topics: