Varying Variables

Posted on 23. Feb, 2010 by admin in Basics


Just printing out text with echo is not going to do us that good, because 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. Just as you used them 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, if you have programmed before, PHP automatically converts variables 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>

The way variables work is you put the dollar sign ($) and then put the variable name after it. Something like this: $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 an 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.


<html>
<body>

<?php
//An integer that stores numbers
$integer = 1;
//An string that stores text
$string = "Hello World ";
//Print out the variables
echo $string;
echo $integer;
?>

</body>
</html>

This code should output “Hello Word 1.” If you are getting any errors, make sure that you have that semicolon, and your variable name does not violate any naming rules.