What is += used for?

前端 未结 11 1842
醉酒成梦
醉酒成梦 2021-01-12 02:00

I think this is a dumb question but I could not find it on php. Why is a + with the = in the following code:

function calculateRanking()
{
    $created = $th         


        
相关标签:
11条回答
  • 2021-01-12 02:38

    There are lots of these shorthand operators in C, C++ in other modern languages.

    a -= b;   // a = a - b;
    a *= b;   // a = a * b;
    a &= b;   // a = a & b;
    

    etc., etc., etc.

    0 讨论(0)
  • 2021-01-12 02:42
    $time += $diff['hours'];
    

    is the same as saying

    $time = $time + $diff['hours'];
    
    0 讨论(0)
  • 2021-01-12 02:44

    Shortcut operator for $val = $val + $otherval.

    This only works on numeric values

    0 讨论(0)
  • Also, "a += b" is an expression who's value can be used again immediately,

    (((((a += b) *= c) += d) * e) += f);
    

    is a lot less typing than

    a = a + b;
    a = a * c;
    a = a + d;
    a = a * e;
    a = a + f;
    
    0 讨论(0)
  • 2021-01-12 02:47

    a += 2; is the equivalent of a = a + 2;

    At one time with some languages (especially very old C compilers), the compiler produced better code with the first option. It sticks around now because it's a common idiom and people used to it think it's clearer.

    0 讨论(0)
提交回复
热议问题