Programming Tutorials

Assignment operators in PHP

By: Andi, Stig and Derick in PHP Tutorials on 2008-11-22  

Assignment operators enable you to write a value to a variable. The first operand (the one on the left of the assignment operator or l value) must be a variable. The value of an assignment is the final value assigned to the variable; for example, the expression $var = 5 has the value 5 (and assigns 5 to $var).

In addition to the regular assignment operator =, several other assignment operators are composites of an operator followed by an equal sign. These composite operators apply the operator taking the variable on the left as the first operand and the value on the right (the r value) as the second operand, and assign the result of the operation to the variable on the left.

For example:

$counter += 2; // This is identical to $counter = $counter + 2;
$offset *= $counter;// This is identical to $offset = $offset * $counter;

The following list show the valid composite assignment operators:

+=, -=, *=, /=, %=, ^=, .=, &=, |=, <<=, >>=

By-Reference Assignment Operator PHP enables you to create variables as aliases for other variables. You can achieve this by using the by-reference assignment operator =&. After a variable aliases another variable, changes to either one of them affects the other.

For example:

$name = "Judy";
$name_alias =& $name;
$name_alias = "Jonathan";
print $name;

The result of this example is

Jonathan

When returning a variable by-reference from a function, you also need to use the assign by-reference operator to assign the returned variable to a variable:

$retval =& func_that_returns_by_reference();





Add Comment

* Required information
1000

Comments

No comments yet. Be the first!

Most Viewed Articles (in PHP )

Latest Articles (in PHP)