Can I re-use an Array?

I could use some help better understanding how Arrays work, including “scope”…

When my Form is submitted, I am creating an array to hold Answers like this…

	foreach($_POST['answerArray'] as $q => $a){
		// Copy data from POST to PHP array.
		$answerArray[$q] = trim($a);

Shortly after populating the $answerArray, I need to iterate through it again, so I did this…

	foreach($answerArray as $questionID => $answer){

Notice how I changed the variable names for fear that these two blocks of code would collide and blow up?!

Now I am at the bottom of my script, and I would like to access the $answerArray a 3rd time to dynamically build the Questions and Answers on my Form itself.

1.) Can someone help me better understand the scope of the Array itself?

2.) Can someone help me better understand the scope of the Key and Value variables?

3.) Did I need to change the “Key” and “Value” variable names between the two blocks of code above?

4.) What do I need to do for this 3rd use of the Array when I try to dynamically create my Form Fields?

Hope that makes senses?!



I can not explain every question, but I believe you can use the same key and value name in the next loop. Maybe empty them between the loops.

But I am wondering why you are doing the same loop three times. Is it not possible to do everything you want to do in one loop?

It sets those key and value pairs each time it iterates through the loop. A loop doesn’t have a scope of its own. When the loop ends $q and $a will keep the last value they were assigned. You can use $q and $a in the second loop and it will be fine.

The only time you may have problems is when using the array by reference. (this doesn’t apply to your questions or code samples here but is for information)

$a = array( 1,2,3 );
foreach( $a as &$v ) { // Note the &
  echo "{$v}\
$v = 5;
array (
  0 => 1,
  1 => 2,
  2 => 5,