Php Tutorial: PHP Expressions and Operators I
PHP Expressions & Operators
Whatever you write in php are expressions, however, it may be an assigned value to a variable or a function which do some operations. In this lesson we get more familiar with them. Operators are signs that do something on variables and save the result into another or the same variable. These operations are some one kind of expressions.
To make Arithmetic expressions, such as summing, we have these basic operators:
· + : Adding one value (directly or from a variable) to another
· - : Subtracting one value from another
· * : Multiplying one value by another
· / : Dividing one value by another
· % : Remained value from dividing
The assignment signs are used to save a value in a variable or an array. The basic one of them that you have saw it before is ‘=’, equal sign. It gets its right-side value and saves it to the variable (or array) which is in the left side. We had some examples in variable lessons. It is not important either the variable has a value or not, once you use this sign a new value goes into the variable. It can also be used for saving one variable value, with or without doing some operation on it, to another variable:
$a= 1+5; // $a= 6
$b= $a; // $b= 6
$c= $a*8 // $c= 48
What is the order when we use some operators with each other? For example what is the answer of ‘3+5*6%35+6/3’ expression? We can use parentheses to avoid confliction. It is prior to other operators; The second place is for multiplication, dividing and percentaging signs (‘*’, ‘/’, ‘%’); The one at left acts before others. The third place is for summing and subtracting (‘+’, ‘-‘); and again the left operator is prior to others.
Another assignment sign that is introduced before (for arrays) is ‘=>’. Examples exist there. So now it is easy to calculate the answer of above expression. First we have ((5*6=30)) then the next is ((30%35=30), after that ((6/3=2)) and finally ((3+30+2=35)).
We have some operators for briefness; they are a combination of assignments and arithmetic operators:
· ++ : Add one to a variable
· -- : Subtract one from a variable
· +=num : Add num to a variable
· -=num : Subtract num from a variable
· *=num : Multiply a variable by num
· /=num : Divide a variable by num
· %=num : A variable value becomes its remained value from dividing of it by num
Here are some examples:
$a= 5; // $a= 6
$a += 6; // $a= 5+6= 11
$a-- // $a= $a-1= 10
$a= ($b=4)+1 // first $b=4 then $a= 4+1=5
Enough for this lesson
You can leave comments once you sign in/up.