In variables begins with a dollar sign ($), and must be followed either by an underscore (_) or a letter (A-Z).
Variables refer to a specific memory location, so that information stored can be easily accessed and manipulated later.
In object oriented PHP, where variables are found inside classes, they will often be referred to as properties.
Use of Variables
You should use variables when you want to save information temporarily for later use.
The below example outputs "My name is Santa" in two different ways, both uses the information we stored in the variable $MyName.
<?php $MyName = 'Santa'; echo 'My name is ' . $MyName; // Using String Concatenation echo "My name is $MyName"; // Using Double Quotes ?>
Storing something in a variable, will allow you to use the variable throughout the script, if you want to store the information for longer then that, you may want to consider using a database, or session variables.
The data types of your Variables is automatically determined doing execution of your script, therefor you don't need to worry about this. However it is a good idea to read up on it, as in languages like c/c++ asigning data types is done manually.
PHP Data Types:
The Numeric types are:
The Integer Type contain number values, while the Double Type contain floating point values, see below:
<?php $Num = 100; // Integer $FloatingNum = 99.5; // Double ?>
The String Data Type
Is used to contain textual information like:
<?php $MyName = 'Santa'; // Only letters $WhoIs = 'Santa the 1th'; // A combination of letters and numbers ?>
The Array Data Type
Is used to easily store many values, in a single variable. This can be done the following ways:
<?php $UserInformation = 'Santa'; $UserInformation = 'The 1th'; $UserInformation = 'Active:Admin'; // The above can also be set the following way. $UserInformation = array('Santa','The 1th','Admin'); // The key value dosn't need to be a number, we can also use a string like below. $UserInformation['Name'] = 'Santa'; $UserInformation['UserCount'] = 'The 1th'; $UserInformation['Status'] = 'Active:Admin'; ?>
Arrays might seam complex at first, but they should be easy to work with, knowing the above.
Another aspect of strings is refereed to as "String Concatenation", this allow you to connect multiple strings, and variables using the "." dot operator.
<?php $MyName = 'Santa'; $MyString = 'My name is: ' . $MyName; // With multiple variables $MyName = 'Santa'; $UserStatus = 'Active:Admin'; $MyString = 'My name is: '; echo $MyString . $MyName . "\n" . 'UserStatus: ' . $UserStatus; ?>
Get the syntax right, and you can enter in just about anything, just like you would in your own language.
The "\n" is just a simple linebreak, the reason we use Double Quotes around it, is to make it appear as a linebreak in the final output. If use Single Quotes instead it will appear as the literal characters "\n" instead of the desired linebreak.