SitePoint Sponsor

User Tag List

Results 1 to 3 of 3
  1. #1
    SitePoint Wizard DoubleDee's Avatar
    Join Date
    Aug 2010
    Location
    Arizona
    Posts
    3,528
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)

    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...
    PHP Code:
        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...
    PHP Code:
        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.


    Questions:
    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?!

    Thanks,


    Debbie

  2. #2
    SitePoint Enthusiast
    Join Date
    Apr 2008
    Location
    The Netherlands
    Posts
    44
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    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?

  3. #3
    SitePoint Evangelist
    Join Date
    Oct 2005
    Location
    Michigan, USA
    Posts
    434
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    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)

    Code PHP:
    $a = array( 1,2,3 );
    foreach( $a as &$v ) { // Note the &
      echo "{$v}\n";
    }
    $v = 5;
    var_export($a);
    Code:
    array (
      0 => 1,
      1 => 2,
      2 => 5,
    )
    - Robert


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •