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
  • 231
  • 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
  • 620,600
  • 104
  • 758
  • 828
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
  • 16,472
  • 26
  • 116
  • 210
spas
  • 1,906
  • 13
  • 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
  • 334,458
  • 66
  • 409
  • 405
0
function makestring($array)
  {
  $outval = '';
  foreach($array as $key=>$value)
    {
    if(is_array($value))
      {
      $outval .= makestring($value);
      }
    else
      {
      $outval .= $value;
      }
    }
  return $outval;
  } 
joe
  • 33,193
  • 29
  • 98
  • 135