Getting a Handle on Data: Variables


So far, the messages we've displayed have been fixed and unvarying, like this:

 <?php     echo "Hello from PHP."; ?> 

This just displays some string text and not much moreand if that's as far as you could go with PHP, you might as well stick with HTML. But PHP is actually about handling your data in a dynamic way, and we're going to start taking a look at how that works now, using variables.

Variables are containers for your data. For example, say you are selling party hats on the web, and you want to check your current total inventory in all three of your warehousesChicago, Tokyo, and Paris. To do that, you'll need to be able to add together those three separate values. PHP comes with all kinds of support built in for performing math operations on your data, including adding. So, to add values, you can use the + operatorfor example, the following script will print out "I have 6 tomatoes":

 <?php     echo "I have " , 1 + 2 + 3 , " tomatoes"; ?> 

Note that we're using numbers here, which is different from straight textbecause the numbers aren't text, they're not quoted. This result is fine, but again, it's static because we've simply put 1 + 2 + 3 in our PHP script. How about being able to add the number of party hats in your warehouses in Chicago, Tokyo, and Paris when the script runs?

That's where variables come in. Variables can hold current data and make that data accessible to you at run time. In PHP, variables start with a dollar sign, $. Variables can store data, so if you're storing the number of party hats in variables named $chicago, $tokyo, and $paris, here's how you could add together those values at run time:

 <?php     echo "I have " , $chicago + $tokyo + $paris , " party hats!"; ?> 

In PHP, a valid variable name starts with a letter or underscore, followed by any number of letters, numbers, or underscores, and the name can be of any length. Here are some valid variable names: $pizza_temperature, $_number_of_tigers, $planet_number_9.

As you can see, variables act as repositories for data. But how do you store that data in variables in the first place?



    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