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

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

提交回复
热议问题