Variables and Operators

  • Description : In this tutorial we will learn how to use variables in PHP and how we can use operators.
  • Language : PHP
  • Date Added : 10th October, 2009
Bookmark and Share

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 :
<?php $variableName = variableValue; ?>

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 :
<?php $varOne = 12; $varTwo = "Twelve"; ?>

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:

  • A variable name must start with a letter or an underscore(_) - not a number
  • A variable name can only contain the following characters:
    • a-z
    • A-Z
    • 0-9
    • Underscore ( _ )
  • No spaces are allowed, either use an underscore or capitalize the start of each new word

You can output the value of a variable on the screen. To do this you use the following code:

Code :
<?php $variableOne = "I am a string!"; echo $variableOne; ?>
Output:
I am a string!

You can also combine two string variables by using this code:

Code :
<?php $variableOne = "My name is "; $variableTwo = "Ashley"; echo $variableOne . $variableTwo; ?>
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:

Mathematical Operators

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

Comparison Operators

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.



Login Required

To post comments you must sign in to your account below!

User :
Pass :

If you do not currently have an account click here to create one now!