Welcome to another tutorial - in this tutorial we aim to teach you how to use variables and operators within PHP code.
Let's start off by looking at the syntax of a PHP variable. The code is below:
Code :
Firstly a PHP variable is always signified by using a dollar sign($). To assign a value to a variable you use an equals sign(=) with the value you want to set after. Below are some examples of how to set a value:
Code :
If you have done programming before in other languages such as Java you're required to define the type, such as an integer or a string, however PHP will decide for itself what type to set. There are some naming rules to consider within PHP:
You can output the value of a variable on the screen. To do this you use the following code:
Code :
Output:I am a string!
You can also combine two string variables by using this code:
Code :
Output:My name is Ashley
As you can see above you output two variables in one echo statement using a full stop. In all languages there are common operators, below are the main ones for PHP:
| Symbol | Operator Name | Example | Result |
|---|---|---|---|
| + | Addition | $var=5; $var+10; |
15 |
| - | Subtraction | $var=10; $var - 3; |
7 |
| * | Multiplication | $var=2; $var*10; |
20 |
| / | Division | $var=10; $var / 2; |
3 5 |
| ++ | Increment | $var=1; $var++; |
2 |
| -- | Decrement | $var=10; $var--; |
9 |
| Symbol | Comparison Name | Example |
|---|---|---|
| == | is equal to | 1==1 returns true |
| != | is not equal | 1!=1 returns false |
| > | is greater than | 1>4 returns false |
| < | is less than | 1<4 returns true |
| >= | is greater than or equal to | 2>=5 returns false |
| <= | is less than or equal to | 2<=5 returns true |
There are other operators, such as Logical operators, but we will cover those when we need to in the IF statements tutorial. This concludes another tutorial, in the next tutorial we will cover Arrays.
To post comments you must sign in to your account below!
If you do not currently have an account click here to create one now!