RafaelM
RafaelM

Reputation: 159

Insert array contents into a string

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!

Upvotes: 2

Views: 3469

Answers (3)

Kristoffer Bohmann
Kristoffer Bohmann

Reputation: 4094

$array1 = array("http://www.example.com/1", "http://www.example.com/2");
$array2 = array("http://www.example.com/3", "http://www.example.com/4");
echo implode(", ", array_merge($array1,$array2));

Output:

http://www.example.com/1, http://www.example.com/2, http://www.example.com/3, http://www.example.com/4

Upvotes: 0

Dagg Nabbit
Dagg Nabbit

Reputation: 76736

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

Upvotes: 1

Jacob Relkin
Jacob Relkin

Reputation: 163258

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

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

echo $csv; //blah,blah,blah,blah

Upvotes: 2

Related Questions