PHP – Foreach Pass-by-Reference ? Do it now!

Normally, when we are using the “Pass-By-Reference” in the foreach block we write code like below..

foreach ($array as &$row) {
// we Just Do Our stuff
}

We Must Have to “Unset” when we use “Pass-by-Reference”. Otherwise the array data may be altered. So, BEWARE.!

foreach ($array as &$row) {
// We Just Do Our stuff

// Now Unset after the Stuff
unset($row);
}

Don’t forget to “unset” the reference variable after the loop.

//---------------------------------
// Normally we do
//---------------------------------

$main_array = array('1','2','3','4');
$sub_array = array('11','22','33','44');


print_r($main_array);

print_r($sub_array);


/*
# Actual Array Data:
Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
)
*/

$main_text = "";
foreach($main_array as &$row) {
    $main_text .= $row.',';

}

$sub_text = "";
foreach($sub_array as $row) {
    $sub_text .= $row.',';
}


print_r($main_array);

print_r($sub_array);



/*

# (main_array) Altered Data:

Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 44
)

# (main_array) Expected Data:

Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
)
*/

//-------------------------------
//	We Have to Use Like this
//-------------------------------

$main_text = "";
foreach($main_array as &$row) {
    $main_text .= $row.',';

    //Unset the pass-by-reference variable
    unset($row);
}

/*
// Now the Result will not altered

Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
)
*/

This is because when the second loop executes, $row is still a pass-by-reference variable.
Thus, with each iteration the original reference is overwritten.

Leave a Comment