views:

57

answers:

2

Hello,
I am trying to insert the contents of an array in to a string using PHP. My array ($array1) looks like this:

Array1  
    (  
       [0] => http://www.example.com/1  
       [1] => http://www.example.com/2  

    )

I want to insert both links in to a coma separated string, so I can then insert it in to a database field.

I tried this:

foreach ($array1 as $name => $value) {
          $string1 .= $value . ",";
          }
  echo $string1;

Which does work, but I am doing this twice in my code for another array that I also want in a separate string ($string2)

    Array2  
    (  
       [0] => http://www.example.com/3  
       [1] => http://www.example.com/4  
    )

When I echo $string1 I get the correct output
http://www.example.com/1,http://www.example.com/2

But $string2 becomes this:
http://www.example.com/1,http://www.example.com/2,http://www.example.com/3,http://www.example.com/4

This happens even if I use different variable names in the foreach loop above.

Someone else also suggested I try this:

$string1 = implode(',' , $array1);  

But I'm not getting any output.

Any help as to how to solve this, or any different approach is greatly appreciated!

+1  A: 

There's a PHP function called implode for this exact purpose.

$csv = implode(',', $array);

echo $csv; //blah,blah,blah,blah
Jacob Relkin
Implode, mentioned in OP. Looks like he expected it to output something.
no
heh, this said `explode` before. Knew I should have kept quiet for 5 more minutes ;)
no
+1  A: 

implode should work fine. It's won't give you any output unless you echo or otherwise output the result, of course.

no
I'm echoing of course after the implode, still no output though
RafaelM
Well then, something else is wrong. Post more code. :)
no
argh just noticed why I got no output after implode. I was using the wrong variable name. Thanks!
RafaelM
Heh. Posting code helps... just make sure you read it while you're posting; you may find you don't need to ask anything after getting a fresh look at it. Sounds silly but it's happened to me more than once, now I just paste a scaled down copy into another buffer and take a fresh look at it.
no
Yes, this is a small script I'm writing to learn programming. Extracting the code from the rest of the script definitely helps. Also, getting up for a while from the computer helps too hehe.Thanks!
RafaelM