Variable Assignments
http://www.mlinux.org/
by Keith Geffert

Hanging on to those pesky tid bits

     Variables are the corner stone of programming. They are the most widely used programming construct. Knowing how to use them is vital to all programming concepts and more advanced language features. If you can't master this then you can't master anything else.

Types of variables

  • Integer -- 1,2,3,4,5 etc.
  • Float -- 13.48434 etc.
  • array -- contiguous set of variables accessed by index number ie array[i]
  • String -- "Hello World"
  • Object -- A special type that encapsulates code AND data

Variable assignments

In php variable assignments follow perl/C syntax. On the left is the name of the variable to be assigned. On the right is the value to assign it. In the middle is the assignment operator which is designated by an '=' sign. Such as.
$foo = 3;
This also represents a complete php "statement". the variable $foo (all variables are referenced inside php code with a dollar sign ) is asigned the value of 3. The semicolon at the end of the line tells php that this is the end of this statement.

Unlike other languages and similar to that of perl and shell languages, variables do not have to be directly declared before being used. In some languages like C, variables must be declared before being used. Like:
int counter;       /* Declare var counter as an Integer */

counter = 1;
C variables are also strictly typed. Once var counter is declared as an Integer all values store in counter will always be an Integer. If you try to assign a string value to counter you will recieve a warning when compiling your C program. Conversely, php is a non strict typing language, it is completely legal to do something like this:
$foo = 3;
$foo = "Hello World";
Here foo is assigned the value of 3. If this is the first time foo is used, it is created for use. Immediately aftewards foo is assigned a string value of "Hello World". Foo is now a type of string and has the value of "Hello World". The previous integer value is lost and forgotton.

Array variables

Arrays are special variables. They actually contain a set of variables that are accessible via a single variable name. Arrays are indexed (indexes are integers) for easy retrieval and storage. To access an array value you give the variable name with the index operator [] inside the index operator is the index value to operate on. IE:
$foo[0] = 3;
$foo[1] = "Hello World";
The first statement assigns the value 3 to the first (arrays start at index 0 unless otherwise declared to start at a different index) index. The second statement assigns the value "Hello World" to the second array position. Unlike C, php is not strictly typed. Arrays in php can have values of different types in the SAME array. In C you cannot assign a string to an array that has been previously declared as some other type.





Previous       Next