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."";
          }/*  ww  w .j  a  v a  2  s .  c om*/

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

          print_r ($authors);
?>

Result

Related Topic