Information Technology Reference
In-Depth Information
IV
Variables are defined with the dollar sign, the name of the variable, and the value:
$color=White
Now, every time you include $color in your script, PHP will return the value White .
In programming, strings are collections of words and characters. In PHP, strings are surrounded
by quotation marks. Most strings use double quotation marks (“Hello World!”), but if you want the
string interpreted literally, use single quotation marks. This becomes useful when you include a
variable in a string (yes, strings are often in variables, and variables appear in strings). PHP will
return the variable's value only when the string uses double quotation marks. In this command,
you complete a sentence:
echo “The president of the United States lives in the $color House.”;
This command, which uses single quotation marks, describes a variable's value:
echo 'The $color variable currently has the value 'white', but you can change it
easily.';
Variables can only store one value at a time. If the background color for your blog is white, and will
always be white, go ahead and define your $bgcolor variable as white . On the other hand, if you
want to change the background color on specific calendar days, you could write a script that draws
on a list of colors available for each occasion. In this case, you need something more flexible than a
simple variable. You need an array .
The easy way to create an array is through the array() function (see the “Functions” section later
in the chapter for more on functions). To set up a group of background colors to be called on those
special occasions, do this:
$bgcolor = array (“pink”, “yellow”, “teal”, “green”, “violet”, “tan”);
Notice three things about this line:
You declare arrays using the same dollar sign used in simple variables; an array is really just a
variable with multiple values.
Values are represented as strings, in double quotation marks.
The statement, as with all lines in PHP, ends with the “instruction terminator” semicolon. The
statement doesn't work without the semicolon. Never forget that when writing your PHP scripts.
Arrays are composed of keys and values. Remember that programming languages are about trans-
lating what a human wants into something a machine can understand. In the previous $bgcolor
example, the values are the words in double quotation marks, whereas the key is the sometimes-
invisible method the language uses to translate the value.
In this type of array, called an indexed array , order is important because that's where the key is.
Each element in the array has an index number, starting with zero (0). This format is common to
most programming languages, not just PHP. To refer to one item in this array, you point to its index
number, as in this code to turn your background color violet (not pink!):
$bgcolor(4)
Search WWH ::




Custom Search