What is += used for?

前端 未结 11 1841
醉酒成梦
醉酒成梦 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:21

    Let's replace a few things to make it a bit easier to understand.

    The += is just the same as below:

    $time = $diff['days'] * 24;
    $time = $time + $diff['hours'];
    $time = $time + ($diff['minutes'] / 60);
    $time = $time + (($diff['seconds'] / 60)/60);
    
    0 讨论(0)
  • 2021-01-12 02:25

    It's adding all those values to time.

    something += somethingelse
    

    is a shortcut for

    something = something + somethingelse
    

    -Adam

    0 讨论(0)
  • 2021-01-12 02:26

    x += 10 is simply a shorter way to write x = x + 10.

    In this case, the code is finding the time difference in hours from a time difference structure.

    0 讨论(0)
  • 2021-01-12 02:31

    According to your code

    $time += $diff['hours'];
    $time += ($diff['minutes'] / 60);
    $time += (($diff['seconds'] / 60)/60);
    

    are similar to the following:-

    $time = $time + $diff['hours'];
    $time = $time + ($diff['minutes'] / 60);
    $time = $time + (($diff['seconds'] / 60)/60);
    
    0 讨论(0)
  • 2021-01-12 02:32

    I just wanted to add that this information is, indeed, on PHP's website in the section on operators, or more specifically, assignment operators.

    0 讨论(0)
  • 2021-01-12 02:33

    If both operands are arrays, $a += $b is also a shorthand for array_merge($a, $b). This function combines two arrays into one, discarding any key in $b that already exists in $a.

    $arr1 = array(4 => "four", 1 => "one", 2 => "two");
    $arr2 = array("three", "four", "five");
    $arr1 += $arr2;
    print_r ($arr1);
    
    // outputs:
    Array
    (
        [4] => four
        [1] => one
        [2] => two
        [0] => three
    )
    
    $arr1 = array(4 => "four", 1 => "one", 2 => "two");
    $arr2 = array("three", "four", "five");
    $arr2 += $arr1;
    print_r ($arr2);
    
    // outputs:
    Array
    (
        [0] => three
        [1] => four
        [2] => five
        [4] => four
    )
    
    0 讨论(0)
提交回复
热议问题