Strange results using references - or is it?

Ask about general coding issues or problems here.

Moderators: egami, macek, gesf

Post Reply
NigelRen
php-forum Fan User
php-forum Fan User
Posts: 622
Joined: Fri Aug 05, 2011 9:53 am

Tue Mar 07, 2017 12:51 am

I'm working with something where I use references to allow me to modify arrays - and the reference on a field seems to 'stick'.

The code I've cut down to show this is...

Code: Select all

<?php
$tableName = "BinType";
$fields = [ 
		[ 
				"name" => "binTypeID"
		],
		[ 
				"name" => "description"
		]
];
foreach ( $fields as $field ) {
	echo " name1='" . $field ['name'] . "' ";
}
$fieldNames = array ();
foreach ( $fields as &$field ) {
	echo " name2='" . $field ['name'] . "' ";
	$fieldNames [] = $field ['name'];
}
foreach ( $fields as $field ) {
	echo " name3='" . $field ['name'] . "' ";
}
Which gives as the output...

Code: Select all

name1='binTypeID' name1='description' name2='binTypeID' name2='description' name3='binTypeID' name3='binTypeID'
So it seems that the reference in the middle foreach seems to be still in place for the last foreach.
Can someone shed some light on this or do I just do what I did and rename the last $field to $field1 and ignore the problem?

( PHP - PHP Version 7.0.15 )

Post Reply