PHP - Reference variable in foreach loop

Introduction

To work with references to the array elements rather than copies of the values, simply add a & (ampersand) symbol before the variable name within the foreach statement:

foreach ($array as  & $value) {

Demo

<?php

          $authors = array("A","B","C","D");

          foreach ($authors as  & $val) {
            if ($val =="C") 
               $val ="Hardy";
            echo $val."";
          }//w  ww  .  j  a v a  2s  .co m

          unset($val);
          echo"\n";

          print_r ($authors);
?>

Result

Related Topic