Assigning Values to Variables


In 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):

 $temperature = 69; $number_of_earths = 1; $pi = 3.1415926535; $reassurance = "No worries."; 

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:

 echo "Setting number of apples to 1.<BR>"; $apples = 1; echo "Number of apples: ", $apples, "<BR>";         .         .         . 

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:

 echo "Setting number of apples to 1.<BR>"; $apples = 1; echo "Number of apples: ", $apples, "<BR>"; echo "Adding 3 more apples.<BR>"; $apples = $apples + 3; echo "Number of apples now: ", $apples, "<BR>"; 

Example 1-4. Assigning values to variables
 <HTML>     <HEAD>         <TITLE>             Assigning values to variables         </TITLE>     </HEAD>     <BODY>         <H1>             Assigning values to variables         </H1>         <?php             echo "Setting number of apples to 1.<BR>";             $apples = 1;             echo "Number of apples: ", $apples, "<BR>";             echo "Adding 3 more apples.<BR>";             $apples = $apples + 3;             echo "Number of apples now: ", $apples, "<BR>";         ?>     </BODY> </HTML> 

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.




    Spring Into PHP 5
    Spring Into PHP 5
    ISBN: 0131498622
    EAN: 2147483647
    Year: 2006
    Pages: 254

    flylib.com © 2008-2017.
    If you may any questions please contact us: flylib@qtcs.net