How to use Variables in PHP
Variables are very important once you start programming in PHP. Variables are used to represent a value and can store numbers, strings or arrays. The main reason variables are so useful is because they can then be used over and over again as many times as necessary.
Here is a simple example of using a variable:
<?php $theVariable = "This is a String"; print $theVariable; ?>
The above code will set the value of $theVariable and then use the print function to print “This is a String” to the screen.
<?php $anotherVariable = 11; print $anotherVariable; ?>
This second example is almost identical to the first except that the variable is assigned an integer value rather than a string. The important thing to notice here is that when assigning an integer value, you do not use the quotation marks, whereas for a string, you place the text between quotes.
If you are familiar with other programming languages, you may think I was a bit sloppy and avoided declaring my variables to save some time and space. This is not the case! PHP is actually a “Loosely Typed Language”. What this means is that variables can be set without being declared; the variable is automatically declared when it is used.
On a final note, as with most programming languages, don’t forget that variables in PHP are case sensitve. $var1 & $Var1 are considered to be two completely different variables. Try and follow some sort of naming convention to avoid errors resulting from this sort of thing.
Leave a Reply