Assigning Values to VariablesIn PHP, when you want to create a variable, you assign data to it using an assignment operator. We'll see all the PHP assignment operators in Chapter 2, "Gaining Control With Operators and Flow Control," but for now, the most common one is the equals sign, =. Here's an example that uses the equals operator to assign values to new variables (after this runs, $temperature will hold 69, $pi will hold 3.1415926535, and so on):
Note that we're assigning numbers to some variables and text to other variables here. In some languages, you need to specify the variable type, such as string or integer, but not in PHP, which makes it much easier. NOTE Internally, however, the computer does use various data types for storage, so in some cases you should know what issues can arise because of data typing. For more on data types, see "Handling Data Types" in this chapter. Take a look at an example, phpvariables.php, which appears in Example 1-4. In this case, we're assigning a value of 1 to a variable named $apples and displaying the value stored in that variable:
Next, say we want to increase the number of apples we have by three. You can do that by assigning $apples the current value in $apples plus 3 and displaying the new result:
Example 1-4. Assigning values to variables
You can see the results in Figure 1-8. Now you can do math at run time, storing data in variables and manipulating that data as needed. Figure 1-8. Assigning values to variables.[View full size image] |
Thursday, November 12, 2009
Assigning Values to Variables
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment