2

Possible Duplicate:
Convert PHP array string into an array

Which function can be used to convert an array into a string, maintaining your ability to return the string into an array?

Community
  • 1
  • 1
Jayu
  • 251
  • 3
  • 5
  • 7
  • duplicate: http://stackoverflow.com/questions/684553/convert-php-array-string-into-an-array – markus Jul 12 '09 at 11:26
  • How can "convert **array** to **string**" question be a duplicate (exact, sic!) of "convert **string** to **array**" question? That are **two exactly opposite** operations! – trejder Mar 26 '15 at 07:44

4 Answers4

7

The serialize function turns any value into a string.

Gumbo
  • 643,351
  • 109
  • 780
  • 844
7

You can use the implode() function to convert an array into a string:

$array = implode(" ", $string); //space as glue

If you want to convert it back to an array you can use the explode function:

$string = explode(" ", $array); //space as delimiter
trejder
  • 17,148
  • 27
  • 124
  • 216
spas
  • 1,914
  • 14
  • 21
4

Just to add, there's also the var_export function. I've found this useful for certain situations. From the manual:

var_export — Outputs or returns a parsable string representation of a variable

Example:

<?php
$a = array (1, 2, array ("a", "b", "c"));
var_export($a);
?>

Returns this output (which can then be converted back to an array using eval()):

array (
  0 => 1,
  1 => 2,
  2 => 
  array (
    0 => 'a',
    1 => 'b',
    2 => 'c',
  ),
)
karim79
  • 339,989
  • 67
  • 413
  • 406
0
function makestring($array)
  {
  $outval = '';
  foreach($array as $key=>$value)
    {
    if(is_array($value))
      {
      $outval .= makestring($value);
      }
    else
      {
      $outval .= $value;
      }
    }
  return $outval;
  } 
joe
  • 34,529
  • 29
  • 100
  • 137