Php: what's the difference between $var and &$var?

前端 未结 5 1807
心在旅途
心在旅途 2021-02-18 22:36

What is the difference between

foreach ($my_array as $my_value) {
}

And:

foreach ($my_array as &$my_value) {
}
5条回答
  •  名媛妹妹
    2021-02-18 22:45

    The first example creates a copy of the value, whereas the second uses a reference to the original value. So after the first foreach runs, the original array is still untouched. After the second foreach the original array could have been modified since it was handled by reference.

    Some native PHP functions already work this way, such as shuffle() which rearranges the contents of your array. You'll notice that this function doesn't return an array, you just call it:

    $myArray = array('foo', 'bar', 'fizz', 'buzz');
    shuffle( $myArray );
    // $myArray is now shuffled
    

    And it works its magic since it works with the array by reference rather than creating a copy of it.

    Then there are functions that don't pass anything by reference but rather deal with a copy of the original value, such as ucwords() which returns the new resulting string:

    $myString = "hello world";
    $myString = ucwords( $myString );
    // $myString is now capitalized
    

    See Passing by Reference.

提交回复
热议问题