PHP Logo

Chapter 2 - Sequence and Variables

By: Albert Ritzhaupt


 


Chapter Topics

Data Types

Like any programming language, PHP supports a multitude of data types. A data type is a characteristic of a field that determines what type of data it can hold.  The PHP scripting language supports eight primitive types that are standard to almost any  programming language (PHP Data Types, 2005). The following table describes each of the data types according to the PHP reference manual. It is important to have a basic understanding of each of the data types and how they are used. 

Name Type Description Examples
boolean scalar This is the easiest type. A boolean expresses a truth value. $foo= True;
$foo= False;
integer scalar An integer is a number without a decimal. $a = 1234;
$a = -123;
float scalar Floating point numbers are those that permit decimal precision. $a = 1.234;
$b = 1.2e3;
string  scalar A string is series of characters (not Uni-Code). echo 'this is a simple string';
echo "He drank some $beers";
array compound See chapter six for details about arrays See chapter six for details about arrays
object compound An abstract data type. Outside the scope of this text.  See the PHP manual.
resource special A resource is a special variable, holding a reference to an external resource. Outside the scope of this text.  See the PHP manual.
NULL special The special NULL value represents that a variable has no value. $var = NULL;

This online book will primarily use floating-point, integer, and String types until chapter 6 when you are introduced to arrays. Chances are that these will be the most important data types you will work with either way.  It is important, however, that you remember there are other data types and you should know where to look to learn about them.

PHP does support other non-primitive data types; however, these data types are outside the scope of this text.  For more information about the other data types or to find more examples of the ones provided here, visit www.php.net.  The remainder of this chapter will focus on using each of the listed data types.

back to top

Working with Variables 

Variables are temporary storing places for information. They can assume the value of something that conforms to one of the data types specified above. For example, a string variable could be assigned the value “hello world” or an integer could be assigned the number 5. "PHP does not require (or support) explicit type definition in variable declaration; a variable's type is determined by the context in which that variable is used (PHP Data Types, 2005)." The figure below illustrates this concept.

$foo1 = "Hello World";  //this variable automatically becomes a string
$foo2 = 5; // this variable automatically becomes an integer
$foo3 = 3.18 //this variable automatically becomes a floating point
$foo4 = True; //this variable automatically becomes a boolean
$foo5 = $foo4; //this variable automatically becomes the type
//that was assigned

Notice that the data type of the variable is based on the assignment of a value to that variable. The word assignment refers to assigning a value to a variable by putting a variable, followed by an equals sign (assignment), and a value or another variable on the right side. The equals sign in PHP means to assign the rights side to the left side.

There are rules that you have to remember as it relates to naming variables.  You should always give variables meaningful names.   This is not a rule of the language, but just good advice.  Important things to remember about naming variables in PHP include: (PHP Variables, 2005)

  • Variables are represented by a dollar sign followed by the name of the variable.
  • The variable name is case-sensitive.
  • A valid variable name starts with a letter or underscore, followed by any number of letters, numbers, or underscores.

Based off of the above rules, you should be able to identify variables that do or do not conform.  It is important that you remember these rules because an error like this will easily lead to a syntax error and a nasty error message.   Below is a table that provides a few examples of variables that do not

Example Valid Reason
$123num NO Following the dollar sign there must be a number or underscore. 
$num1 YES This example is valid.  The number is allowed as long as it is not the first character after the dollar sign.
$$theVar NO You are only allowed to have one dollar sign as part of the variable name and it must be the first character.
$theVar YES This example is valid.  Capital letters are allowed, but keep in mid the language is case sensitive.
$num* NO No special characters are permitted - only numbers, letters, and underscores.

Two very important concepts for you to understand is the scope and duration of a variable.  Scope refers to where the variable is visible for use.  Duration refers to how long the variable will last.  For now, it is safe to assume that a variable used in a PHP web page will be visible to everywhere else after it has been assigned its initial value.  With respect to duration, for now you can assume that the variable will last only once - meaning the only time the PHP page is executed.  It will not last any time after until we talk about sessions.  The example below illustrates the idea.

Assume this code is in one file
<?php echo $a; ?>
<?php $a=1; ?>

In this example, there is no output because the variable is printed via the echo statement before the variable is first initialized. This is an example of where sequence matters.  In this next example, the two are reversed. 

Assume this code is in one file
<?php $a=1; ?>
<?php echo $a; ?>

This time the output would be "1" because the variable is first initialized, and then printed via the echo statement.  You have to assign a value to the variable before it prints anything.  Keep in mind, sequence matters.

back to top

Making Comments in your Code

It is easy to forget what you were working on when you are programming.  That is why it is always a good idea to write comments in your code.  Since every character is accounted for in a PHP program, you have to put comments in your code so that the interpreter will ignore the comments.  This is especially important if you are working with other people.  For instance, imagine someone you were working with wrote a big program then handed it to you to add additional functionality to.  If there were no comments, it would be a long and frustrating process.

There are a two ways to put comments in your PHP program.  The first way is to place "//" followed by your comment.  PHP will ignore anything that comes after the "//".  The other way to place comments in your code is to place "/*" followed by the text your want to be commented followed by "*/".  Using this approach you comment everything that appears within the opening "/*" and the closing "*/".  The figure below provides a few examples.  When you place many Asterisks around a comment, we refer to it as a flower box.

INCORRECT 
This comment would not be because it occurs before.//

/* This one is missing the closing.

CORRECT //This statement would be commented because it occurs after. /*All of this text would be commented because it is within the opening and closing. Be careful, if you leave open without a close, all of your source code will be commented out.*/ /***************************************** * * * This is what we call a flower box. * * * *****************************************/

People will loose their jobs these days for not properly commenting and documenting their source code.  Not only does it frustrate employers, it is unkind to your fellow programmer, so be sure to comment your code properly.

back to top

Concatenation of Strings

Concatenation is a big word for a little idea.  It simply means to append two or more strings together to make one big string.  The syntax for concatenating is pretty simple. You just place a period in between two string variables.  The following provides a few examples of how to concatenate strings.

Concatenate without Space
$foo1 = "Hello";
$foo2 = "World";
$concat1 = $foo1 . $foo2; // no space
echo $concat1;
OUTPUT: HelloWorld

Concatenate with Space $foo1 = "Hello"; $foo2 = "World"; $concat1 = $foo1 . " " . $foo2; // space echo $concat1; OUTPUT: Hello World

Concatenate a Sentence $foo1 = "Hello,"; $foo2 = "Bob"; $concat1 = $foo1 . ", " . $foo2 . "."; echo $concat1; OUTPUT: Hello, Bob.

Concatenation is a handy tool when creating dynamic web pages.  It is also really simple to do.  Notice that you can concatenate both variables and string literals.  String literals are simply values within the double quotes.  You can also create string literals using single quotes. 

back to top

Expressions and Arithmetic

Variables are of little use if you cannot do anything with them.  In PHP, we can do arithmetic calculations with numeric type variables, such as floats and integers.  The most basic form of an expression is assigning a value to a variable as shown in all the examples above.  However, you can also use operators for operations like multiplication or addition.  These operations are essential to a programming language.  The table below shows the arithmetic operators and their precedence: (PHP Arithmetic, 2005).

Example Name Result
-$a Negation Opposite of $a.
$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.

The table above is critical for you to memorize.  Most programming languages use the same syntax for the operations.  All of these operations you should be familiar with with the exception of Modulus.  Modulus simply means the remainder.  Notice that the precedence follows the oder of operations in algebra - (Please - Excuse - My - Dear - Aunt - Sally for Parenthesis - Exponents - Multiplication/Division - Addition/Subtraction.  This is always an easy way to remember.

Keep in mind that parenthesis always override the order of operations.  When parenthesis are involved - go inside to outside, left to right.  The following table provides a few examples only dealing with integers.  You should practice these examples so that you can become proficient.  Don't fear math!  Math is fun!

Equation Result
$a=2;
$b=3;
$c=$a*2+10*$b;
echo $c; 
The result is 34 because multiplication
occurs before addition.
$a=2;
$b=3;
$c=$a*(2+10)*$b;
echo $c; 
The result is 72 because the parenthesis
override the oder.
$a=5;
$b=3;
$c=($a - $b) * 10 % 5;
echo $c; 
The result is 0 because the remainder
of 20 divided by 5 is 0.
$a=5;
$b=3*$a;
$c=$b / $a * 10 % 4;
echo $c; 
The result is 2 because the remainder
of 28 divided by 2 is 2.
$a=5;
$b=-$a;
$c=$b / $a * 2;
echo $c; 
The result is -2 because of the negation
operation .
$a=5;
$b=$a;
$c= 5 + $b * 4 / ($a + $a);
echo $c; 
The result is 7 because parenthesis
override the operation.

All the examples above are pretty straight-forward, but you can imagine that the calculations could easily get very difficult.  In addition to understanding the examples and operations above, you should also learn the increment and decrement operations.  The increment operation is a simple way to add one to the value of a variable.  The decrement operation is a simple way to subtract one from the value of a variable.  The table below shows how the increment and decrement operations work. 

Operation Equivalent Type
++$a $a=$a+1 Prefix
$a++ $a=$a+1 Postfix
--$a $a=$a-1 Prefix
$a-- $a=$a-1 Postfix

This seems pretty easy with the exception of the difference between prefix and postfix.  Prefix means the calculation will occur before the assignment, whereas postfix means it will occur after the assignment.  

back to top

Your Second Program

This section will provide the steps for you to create your second PHP program.

  1. First create a file named "second.php" in a directory that is recognized by the web server. The file should contain the following information:

    <html>
    <h3>Simple Calculations</h3>
    <?php
    $a = 6;
    $b = 2;
    echo "The Value of a = $a <br>";
    echo "The Value of b = $b <br>";
    $c = $a + $b;
    echo "The a + b = $c <br>";
    $c = $a - $b;
    echo "The a - b = $c <br>";
    $c = $a * $b;
    echo "The a * b = $c <br>";
    $c = $a / $b;
    echo "The a / b = $c <br>";
    $c = $a % $b;
    echo "The a % b = $c <br>";
    $c = ++$a + $b;
    echo "The ++a + b = $c <br>";
    $c = --$a + $b;
    echo "The --a + b = $c <br>";
    echo "That's all folks!"; ?>
    </html>

  2. After you have created the file and put the information into the file, save your work, and change the permissions of the file to:

    prompt$: chmod 705 second.php


  3. Open the URL to the location where you saved the file and you should have the following output:

    Simple Calculations 
    The Value of a = 6
    The Value of b = 2
    The a + b = 8
    The a - b = 4
    The a * b = 12
    The a / b = 3
    The a % b = 0
    The ++a + b = 9
    The --a + b = 8
    That's all folks!


    Pay special attention to the result of each of the operations to ensure the anticipated result is the same as the result you received. 

Congratulations! You have completed the second chapter. You can now take the online assessment, complete the second activity, and move to the next chapter. 

>>Take the Online Quiz

back to top

Activity 2

Create a program titled "futureValue.php" to calculate the future value for the following equations.  First create a set of variables: interest, term, payment, and principle.  Assign realistic values to each of these variables.

  1. Payment Compound Interest 
                                            term
    (1+interest) -1)
    future value= payment*------------------ *(1 + interest)
    interest
  2. Simple Interest 
          future value= principal*(1+interest)
  3. Compound Interest
                                            term
    future value= principal*(1+interest)

You program should print the variables, there names, and the three different future value calculations.

back to top

Chapter References

back to top

Previous section Next section

 

Copyright  Albert Dieter Ritzhaupt. All Rights Reserved.