-1

I'm trying to convert a PHP array to a string. This is what the array looks like when I print_r:

Array (
  [0] => Array (
           [0] => Some text
         ) 
  [1] => Array (
           [0] => some more text
         ) 
  [2] => Array (
           [0] => SomeText
         )
)

Here's the code I'm trying to use:

foreach($a as $b){
        $c.= ", $b";
}

But that keeps coming back with Array Array Array.

8
  • how would you like the array to be represented? Commented May 15, 2015 at 20:32
  • I dont understand why would anyone downvote without saying any reason. Commented May 15, 2015 at 20:37
  • They are all wrong and almost the same answer. Commented May 15, 2015 at 20:39
  • @AbraCadaver...so can you remove the downvote now that mine was correct :P Commented May 15, 2015 at 20:46
  • So where are we with this question now? Commented May 15, 2015 at 20:56

5 Answers 5

1

Just initialize your string and then go through each value with array_walk_recursive() and append it to the string. At the end just remove the last comma with rtrim():

$str = "";
array_walk_recursive($arr, function($v)use(&$str){$str .= $v . ",";});
echo $str = rtrim($str, ",");

Advantages? It doesn't matter how many dimensions your array has.

Sign up to request clarification or add additional context in comments.

Comments

0
foreach($a as $b){
        $c.= ", ".$b[0];
}

What you have is actually a multidimensional array. So $b is still an array in this scenario and 0 is the offset you need to retrieve, so therefore you need $b[0].

Comments

0

That is basically and array that contains arrays, so you need to iterate over the inner arrays.

    foreach($a as $b){
    // b is array here
      foreach($b as $actualValues){
      $c.= ",".$actualValues[0];
      }
    }

Comments

0

So given the sample array, it is multi-dimensional. If you want to display the inner array values separated by commas:

foreach($a as $v) {
    echo implode(', ', $v);
}

If all need to be joined into a comma separated list then:

foreach($a as $v) {
    $result[] = implode(', ', $v);
}
echo implode(', ', $result);

6 Comments

I think you're first example is wrong in this case. They are stored in offsets 0,1,2 not all under the first offset 0.
Yes, I hate when it's not indented.
Yeah, I guess I was wrong, I just indented it. It was not how I thought it was.
Oh nevermind, I was right, lol. I just messed up the indentation... wow confusing post.
this would still miss a comma between array entries.
|
-2

You have got an Array, consisting of Arrays with one Element containing your Text. So you are trying to print an Array which contains your string. Try it like this:

foreach($a as $b){
    $c.= ", ".$b[0];
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.