The most basic, core entity in the PHP language is the variable. In common terms, a variable is data stored which is found by its identifier. In PHP, all identifiers are designated with a '$' in front of their name. To initialize a variable, you write its name and set it equal to whatever data you want:
which displays the same result you had before:
The URL for this page is: http://sandersongs.com/PHPsqlCourse/PHP02.php
The advantage to using a variable in the case above is that the computer calculates the value only once, and you can recall the value as often as needed in your script.
There are five basic types of data stored in variables: string (text), integer (number), double (number with decimal values), array and object. More advanced types of data include boolean, resource, NULL and unknown, but these advanced typed of data are not discussed here. Here are some examples of each of the basic types:
- $name = "Fred";
- $day = date('j'); (which reads as 6)
- $dollars = 1000;
- $next = 5%3; (which reads as 2)
- $average = 31.75;
- $meters = 5.0;
- $sixMonths = array('Jan','Feb','Mar','Apr','May','Jun');
- $misc = array($name,$next,$average,$sixMonths);
- $result = new carClass();
- (This is advanced stuff. Save it for the lesson on Object-Oriented Programming.)
Integers and Doubles are somewhat self-explanatory. Note the absence of quotes in initializing a numeric variable. $day = 12; is not the same as $day = "12";. Although PHP is a little forgiving in that it will try to make a string a number and vice-versa if you seem to want it, you will get bizarre results if you are not careful with quotes. Also note the absence of commas in numeric values. $dollars = 1,000; will get you a Parse Error.
Variables can change each time the script is called. That's what makes the language dynamic. Variables can be defined using other variables (eg $avg = ($a + $b)/2; ). Variable names can be of any length (eg $theVeryFirstIntegerThatAppearsAfterZeroAndBeforeTwo = 1; ). Variable names must begin with a letter or underscore (eg $a1234 and $_1234 are legal names for variables). Variable names must contain only letters, numbers and/or underscores (eg $w_3 is legal; $w-3 is illegal). Variable names are case-sensitive (eg $car and $Car are different variables to the computer).
If you initialize a variable, then set it equal to something else, the new value replaces the old. So, if $car = "Buick"; and later you code $car = "Volkswagen"; then the value of $car changed and will remain "Volkswagen" until changed again.