Jump to content

Strange results using references - or is it?


NigelRel3

Recommended Posts

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...

<?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...

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?

 

Thanks

( PHP - PHP Version 7.0.15 )

Link to comment
Share on other sites

Here is what I believe is happening:

 

At the end of the second foreach() loop you have a "$field" variable that is a reference. Then on the first iteration of the third loop the "$fields as $field" within the foreach is taking the first value of the array $fields and setting it as the value of the variable $field - which is still a reference to the second element in the array. So, on that third foreach loop, I think it is actually displaying the value for the second element on both iterations - but you are seeing the first value because it was overwritten on the first instance.

 

Think of it this way for the logic on the last foreach loop:

 

Take the next value from the $fields array and assign it to the 2nd element of $fields. Then display the value of the 2nd element.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.