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

前端 未结 5 1818
心在旅途
心在旅途 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.

    0 讨论(0)
  • 2021-02-18 22:49

    I only use references when i have to read csv files to know what is the delimitier. Just take the first line:

    $handle = fopen($file, "r");
    $firstLine = fgets($handle);
    fclose($handle);
    

    Then with this possible delimitiers

    $delimiters = array(';' => 0,',' => 0,"\t" => 0,"|" => 0);
    

    Count by reference what is the most used

    foreach ($delimiters as $delimiter => &$count) {
        $count = count(str_getcsv($firstLine, $delimiter));
    }
    $delimiter =  array_search(max($delimiters), $delimiters);
    
    0 讨论(0)
  • 2021-02-18 22:51

    A real world example for & use is when you need to change the content of an array with very few lines of code

    foreach($arrFeed as &$objFeed)
      $objFeed['externalSrc'] = convertToLocalImage($objFeed['externalSrc']);
    
    0 讨论(0)
  • 2021-02-18 22:52

    When you prefix a variable with an ampersand, you’re creating a “reference.” PHP references are like shortcuts or symlinks on your computer. You can create a pointer variable that is just another name for the same data.

    I dont see a big difference in using these, except that you DONT COPY a variable saving memory. When you are passing variables you can just pass the reference and the reference points to the original object.

    0 讨论(0)
  • 2021-02-18 23:01

    Jonathan's answers describes it very well. Just for completeness, here are your two examples:

    1. Just reading values:

      $my_array = range(0,3);
      foreach ($my_array as $my_value) {
          echo $my_value . PHP_EOL;
      }
      
    2. Adding some number to each element (thus modifying each value):

      foreach ($my_array as &$my_value) {
          $my_value += 42;
      }
      

      If you don't use &$my_value, then the addition won't have any effect on $my_array. But you could write the same not using references:

      foreach($my_array as $key=>$value) {
          $my_array[$key] = $value + 42;
      }
      

      The difference is that we are accessing/changing the original value directly with $my_array[$key].

    DEMO

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