PHP - Altering Array Values with foreach

Introduction

If you change the value given to you by foreach, you're not affecting the corresponding value in the original array.

The following example code illustrates this:

Demo

<?php

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

           foreach ($authors as $val) {
             if ($val =="C") 
                $val ="Hardy";
             echo $val . " ";
           }//w ww . j  ava 2s  . c o m
           echo"\n";
           print_r ($authors);
?>

Result

Here, although $val was changed from "C" to "Hardy" within the loop, the original $authors array remains untouched.

Related Topic