-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.

Rizier123
  • 58,877
  • 16
  • 101
  • 156
vanquish
  • 125
  • 1
  • 2
  • 12

5 Answers5

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.

Rizier123
  • 58,877
  • 16
  • 101
  • 156
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].

Devon Bessemer
  • 34,461
  • 9
  • 69
  • 95
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);
AbraCadaver
  • 78,200
  • 7
  • 66
  • 87
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];
      }
    }
Danyal Sandeelo
  • 12,196
  • 10
  • 47
  • 78
-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];
}
Speni
  • 32
  • 5