May 27, 2012

Push associated variables into array in PHP

Question by Dev Newb

I have a loop and each time the loop runs I need to add two variables to an array. What I am trying right now is:

$attach_array['outline'] = array();

foreach ($_POST['attachment'] as $key => $value) {
  $attachmentName        = $value['name'];
  $path                  = "1";
  $name                  = "alsdkjf";
  $attach_array['outline']['path']=$path;
  $attach_array['outline']['name']=$name;
}

Then later in the script I try to get these values out for PHPMAILER:

foreach ($attach_array['outline'] as $key => $value) {
   $mail->AddAttachment($value['path'], $value['name']);
}

This and other attempts are not working so I’m hoping for some help on putting $name and $path into an array in my first loop to use later.

Answer by Starx

You are overriding the same variables on each loop. You should do something like this:

  $attach_array['outline'][] = array('path' => $path, 'name' => $name);

By doing this, now all the path and values will remain on the array as separate items. You dont have to change the code you are using it from.

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!