And now let’s see what we can do with the variables in our PHP scripts. First, we’ll learn about PHP operators. Some of PHP operators are vary similar to basic arithmetic from school. Remember addition, subtraction, multiplication, division etc.? The same we can do with PHP variables:
$var1 + $var2;
$var1 – $var2;
$var1 * $var2;
$var1 / $var2;
Do you remember $var1 = “hello”; from our previous tutorial about variables? Well, the “=” is the assignment operator. This is not “equal to”! It means that the left operand is set to the value of the expression on the right.
You can also compare two variable values using comparison operators:
$var1 == $var2; // Result true if $var1 is equal to $var2.
$var1 != $var2; // Result true if $var1 is not equal to $var2.
$var1 > $var2; // Result true if $var1 is greater than $var2 etc.
$var1 < $var2;
$var1 >= $var2;
$var1 <= $var2;
You can increment or decrement your variables by one using incrementing or decrementing operators:
++$var1; // Increments $var1 by one, then returns $var1.
$var1++; // Returns $var1, then increments $var1 by one etc.
You will also need logical operators:
$var1 and $var2 – Result true if both $var1 and $var2 are true.
$var1 or $var2 – Result true if either $var1 or $var2 is true.
$var1 && $var2 – Result true if both $var1 and $var2 are true.
$var1 || $var2 – Result true if either $var1 or $var2 is true.
!$var1 – Result true if $var1 is not true.
We already talked about string concatenation. Example:
$var1 = “PHP is “;
$var2 = $var1 . “easy!”; // $var2 now gets “PHP is easy!”
You can do the same using the concatenating assignment operator (‘.=’):
$var1 = “PHP is “;
$var1 .= “easy!”; // $var1 gets “PHP is easy!”
There are similar addition, subtraction etc. assignment operators:
$var1 = 7;
$var1 += 3; // $var1 now contains 10. This is the same like: $var1 = $var1 + 3;
Well, now let’s see how we can control our variables. Let’s go to the next tutorial PHP control structures.