赋值运算符

基本的赋值运算符是“=”。一开始可能会以为它是“等于”,其实不是的。它实际上意味着把右边表达式的值赋给左边的运算数。

赋值运算表达式的值也就是所赋的值。也就是说,“$a = 3”的值是 3。这样就可以做一些小技巧:

<?php

$a
= ($b = 4) + 5; // $a 现在成了 9,而 $b 成了 4。

?>

在基本赋值运算符之外,还有适合于所有二元算术和字符串运算符的“组和运算符”,这样可以在一个表达式中使用它的值并把表达式的结果赋给它,例如:

<?php

$a
= 3;
$a += 5; // sets $a to 8, as if we had said: $a = $a + 5;
$b = "Hello ";
$b .= "There!"; // sets $b to "Hello There!", just like $b = $b . "There!";

?>

注意赋值运算将原变量的值拷贝到新变量中(传值赋值),所以改变其中一个并不影响另一个。这也适合于在很密集的循环中拷贝一些值例如大数组。自 PHP 4 起支持引用赋值,用 $var = &$othervar; 语法,但在 PHP 3 中不可能这样做。引用赋值意味着两个变量都指向同一个数据,没有任何数据的拷贝。有关引用的更多信息见引用的说明


add a note add a note User Contributed Notes
adam at gmail dot com
26-Aug-2006 01:38
or you could use the xor-assignment operator..
$a ^= $b;
$b ^= $a;
$a ^= $b;
bradlis7 at bradlis7 dot com
15-Aug-2005 11:13
Note whenever you do this

<?php
$a
.= $b .= "bla bla";
?>

it comes out to be the same as the following:

<?php
$a
.= $b."bla bla";
$b .= "bla bla";
?>

So $a actually becomes $a and the final $b string. I'm sure it's the same with numerical assignments (+=, *=...).
trosos at atlas dot cz
03-Jul-2004 09:19
Note that the value of an assignment expression is not the value assigned, but the variable itself (after assign, of course). This allows to do something like this:

<?php

function f(&$a)
{
 ...
}

f($v=3);

?>
straz at mac dot nospam dot com
21-Feb-2004 02:18
This page really ought to have table of assignment operators,
namely,

See the Arithmetic Operators page (http://www.php.net/manual/en/language.operators.arithmetic.php)
Assignment    Same as:
$a += $b    $a = $a + $b    Addition
$a -= $b    $a = $a - $b    Subtraction
$a *= $b    $a = $a * $b    Multiplication
$a /= $b    $a = $a / $b    Division
$a %= $b    $a = $a % $b    Modulus

See the String Operators page(http://www.php.net/manual/en/language.operators.string.php)
$a .= $b    $a = $a . $b      Concatenate

See the Bitwise Operators page (http://www.php.net/manual/en/language.operators.bitwise.php)
$a &= $b    $a = $a & $b    Bitwise And
$a |= $b    $a = $a | $b      Bitwise Or
$a ^= $b    $a = $a ^ $b      Bitwise Xor
$a <<= $b    $a = $a << $b    Left shift
$a >>= $b    $a = $a >> $b      Right shift
jeronimo at DELETE_THIS dot transartmedia dot com
29-Jan-2004 11:27
If you want to swap values between variables without using an intermediary, try using the list() and array() language constructs. For instance:

<?

// Initial values.
$biggest = 1;
$smallest = 10;

// Instead of using a temporary variable...
$temp = $biggest;
$biggest = $smallest;
$smallest = $temp;

// ...Just swap the values.
list($biggest, $smallest) = array($smallest, $biggest);

?>

This works with any number of variables; you're not limited to just swapping two.
Cheers,
Jeronimo