PHP Basics : Variables
Variables in PHP, just like any programming language, are used for storing values, such as text strings, numbers, or an array of values. Once you have declared, a variable, it can be used over and over again throughout your script.
Variables in PHP must be declared with a ‘$’ symbol. So a variable named test would be declared as $test. The ‘$’ symbol is also needed every time the variable is used after it is declared.
A simple variable declaration should be done as followed :
Now let’s make one variable with a string, and another with a number value :
- Note – A string, like the echo statement, can use either single or double quotes, but it must end with whichever it starts with.
There is a lot of freedom when using variables in PHP. First of all you do not have to declare the variable before it is used. The first time you use the variable it will be declared. You also do not have to declare the data type (string, integer, float) of the variable. Once you use the variable, PHP automatically changes the data type to whatever value is stored in the variable.
You can also change the data type of the variable multiple times in your script. Example :
- Note – This can be done as many times during your script as you’d like.
With all the freedom that comes with PHP variables, there are some rules when it comes to naming them :
- PHP variable names must start with a letter or an underscore.
- PHP variable names can consist of only alpha-numeric characters and underscores: a-z, A-Z, 0-9, and _
- A PHP variable name cannot contain spaces. If a variable is more than one word use an underscore in between them such as ‘$my_variable’ or use capitalizations like ‘$myVariable’.
Now let’s make a simple PHP script that can show us the effects of using variables :
So what’s going on here? First we set a variable to equal the string ‘Hello World!’, then another variable to equal the number ’23′. After that we used the echo command to print on screen what was stored in the ‘$hello’ variable. The second echo statement prints a string followed by the ‘$fav_num’ variable.
- Note – In the second echo statement, to connect the string to include the ‘$fav_num’ variable, we use a period in between the two. This is known as concatenation, or to concatenate.
When you open your newly made script in a browser it should look something like this :
That pretty much covers the basics of PHP variables. Try to write some scripts with what you’ve learned to get used to using variables. A good thing to try also, is naming the variables something that isn’t recommended, just to see what the error looks like that PHP would likely spit out.
As usual if you’ve got any questions, just comment below.
- PHP Basics : Introduction To PHP
- Easy PHP Guestbook Part 4 – Submitting to the Database
- Easy PHP Guestbook Part 5 – Retrieving from the Database
- Book Review: Core Data iOS Essentials
- HowTo: Send Text Messages For Free With Email