Varying Variables
Posted on 23. Feb, 2010 by admin in Basics
Simply typing in text messages with echo is not going to assist us in utilizing PHP to its fullest potential, we can just as easily do that in HTML. The real power comes from something called variables. Just as you probably used the variable X for math equations or to store numbers, programming variables can store much more including text and sets of data. There are two types of variables that you need to know about right now, though there are many more:
- Integers – Stores numbers like 1, 39, 519.
- Strings – Stores text like “Hello World”, “I love PHP,” “WildPHP is cool.”
Unlike some of the other scripting languages, PHP automatically converts variable types for us. Take a look at the code below and then we will break it down.
<html> <body> <?php //An integer that stores numbers $integer = 1; //An string that stores text $string = "Hello World"; ?> </body> </html>
Variables work when you place the dollar sign ($) and then put the variable name after it (for example: $variablename). Now there are some rules that you must follow:
- Must start with a letter or an underscore ( _ )
- Can only use alpha-numeric characters(a-z, 0-9) and underscores ( _ )
- A variable name can not contain a space. Use underscores ( _ ) instead.
We set the value of the variable by adding an equal sign (=) and putting the value we want to set it to on the right. Like the echo statement, we must end this with a semicolon (;). To make sure this works correctly lets print our variables by putting them after the echo statement. Echo will print out the value of the variable or statement that comes after it to the screen.
<html> <body> <?php //An integer that stores numbers $integer = 1; //An string that stores text $string = "Hello World "; //Print out the $string variable echo $string; //Print out the $integer variable echo $integer; ?> </body> </html>
Output:
Hello World 1
If you are getting any errors, make sure that you have that semicolon, and your variable name does not violate any naming rules.
Note: If you are confused why it prints out “Hello World 1″ instead of “1 Hello World,” it is because $string, which contains “Hello World ” is printed first with echo. It does not mater the order of our variables above, just the order they are printed with echo.

