The Assignment Operators


The main assignment operator is =, which assigns a value to a variable:

 $oranges = 12; 

That's one we've already seen. You can do some tricky stuff with the = operator, such as the following, where we're setting three variables to the same value, 1:

 <?php     $a = $b = $c = 1;     echo $a, ", ", $b, ", ", $c;  ?> 

Here's what you see when you run this script:

 1, 1, 1 

Besides the basic assignment operator, there are "combined operators" for all the binary arithmetic and string operators that allow you to use a value in an expression and then set its value to the result of that expression. Here are the combined operators (we'll see the various operators that are combined with the = sign here in this chapter):

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

These operators can save you a step; for example, say you wanted to add 10 to the value in the variable $my_CD_collection. You could do that like this:

 $my_CD_collection =  $my_CD_collection + 10; 

Using the combination operator += gives you a shortcut, letting you combine the addition and the assignment into one operation:

 $my_CD_collection +=  10; 

Not bad. Here's another example, using the string concatenation operator, ., and the division operator, /:

 <?php     $text = "No ";     $total = 150;     echo $text .= "worries.<BR>";     echo "Average = ", $total /= 3, "<BR>"; ?> 

Here's what you get from this script:

 No worries.<BR>Average = 50<BR> 



    Spring Into PHP 5
    Spring Into PHP 5
    ISBN: 0131498622
    EAN: 2147483647
    Year: 2006
    Pages: 254

    flylib.com © 2008-2017.
    If you may any questions please contact us: flylib@qtcs.net