364

What is the best method for converting a PHP array into a string?
I have the variable $type which is an array of types.

$type = $_POST[type];

I want to store it as a single string in my database with each entry separated by | :

Sports|Festivals|Other
5
  • 25
    Please refrain from inserting serialized values into a database. Here's why: stackoverflow.com/questions/7364803/… Commented Sep 20, 2011 at 19:15
  • 14
    @NullUserExceptionఠ_ఠ I agree that inserting serialized values into the DB just absolutely burns eyes, but you don't know his situation - it very well maybe warranted. Commented Sep 21, 2011 at 6:26
  • 4
    I think that this question should be reopened. It is useful question for beginners and I don't think it is off-topic.
    – SaidbakR
    Commented Feb 23, 2014 at 16:47
  • 1
    what if some of the values in array have chars | Commented May 20, 2014 at 11:22
  • You can then escape those characters. Read it in here. php.net/manual/en/regexp.reference.escape.php Commented Feb 26, 2018 at 13:03

13 Answers 13

441

Use implode

implode("|",$type);
3
  • 18
    This is good unless you have nested arrays - which can happen with $_POST if you're using array-named form inputs.
    – Leith
    Commented Oct 24, 2016 at 4:47
  • with nested arrays just use a foreach it will work. Commented Mar 26, 2019 at 13:31
  • @devasia2112 foreach for nested array will not be a good/efficient solution.... if it is multi level nested ? and if somewhere depth is 2 and some where 3 ? it will be too much overhead and program complexity will be worse in that case ! Serializing is far better in this case.
    – Alice
    Commented Aug 13, 2021 at 5:35
278

You can use json_encode()

<?php
$arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);

echo json_encode($arr);
?>

Later just use json_decode() to decode the string from your DB. Anything else is useless, JSON keeps the array relationship intact for later usage!

7
  • 51
    "Anything else is useless"... except perhaps normalizing the data.
    – Dan Lugg
    Commented Jun 17, 2013 at 19:51
  • 7
    Rofl @ comment above me. As you say, blanket statements are almost always, unhelpful.
    – Aaron Cole
    Commented Aug 20, 2013 at 23:17
  • 14
    I'm glad you guys are entertained :)
    – Jakub
    Commented Aug 23, 2013 at 14:52
  • 18
    "Sweeping generalizations, as well as absolutes, are always wrong. Always." ;)
    – Olie
    Commented Oct 12, 2015 at 21:52
  • 1
    I like that this one keeps the keys. This is very useful for later use.
    – Apolymoxic
    Commented Jul 16, 2019 at 22:29
56
json_encode($data) //converts an array to JSON string
json_decode($jsonString) //converts json string to php array

WHY JSON : You can use it with most of the programming languages, string created by serialize() function of php is readable in PHP only, and you will not like to store such things in your databases specially if database is shared among applications written in different programming languages

3
  • 1
    JFI in my use I had to call $data= json_decode($jsonString, true) Commented Oct 14, 2016 at 6:57
  • second argument is optional, in most of the case it works without that. Commented Dec 21, 2016 at 18:58
  • 1
    This works for single or multi dimension arrays excellent and in my opinion this should be the accepted answer. Also consider adding true as a second parameter.
    – Combine
    Commented Mar 14, 2017 at 11:33
46

One of the Best way:

echo print_r($array, true);
4
  • 13
    please elaborate on your answer, showing how it solves the problem Commented Jun 18, 2014 at 11:47
  • 1
    You can also use: "print_r($array, false);", as this will print the array without returning a value. If true is given, print_r() won't print on it's own and will simply return the string. More at: php.net/manual/en/function.print-r.php
    – Garrett
    Commented Sep 2, 2016 at 18:42
  • 1
    This one should be the best one since json_decode messes up with the format causing confusion. Commented Jun 16, 2017 at 19:28
  • it was requested to store the string in the db, not to print it
    – Mark
    Commented Jul 2, 2020 at 10:05
38

No, you don't want to store it as a single string in your database like that.

You could use serialize() but this will make your data harder to search, harder to work with, and wastes space.

You could do some other encoding as well, but it's generally prone to the same problem.

The whole reason you have a DB is so you can accomplish work like this trivially. You don't need a table to store arrays, you need a table that you can represent as an array.

Example:

id | word
1  | Sports
2  | Festivals
3  | Classes
4  | Other

You would simply select the data from the table with SQL, rather than have a table that looks like:

id | word
1  | Sports|Festivals|Classes|Other

That's not how anybody designs a schema in a relational database, it totally defeats the purpose of it.

9
  • 2
    sure it is, you dont have to escape the delimiters!
    – Chris G.
    Commented Sep 20, 2011 at 19:16
  • 2
    @MarcB It makes the encoding idiot-proof, standard, prone to less bugs, and easily exportable back to an array. Should he use another table? Probably. Is this better than everyone saying implode? Absolutely.
    – Incognito
    Commented Sep 20, 2011 at 19:17
  • 7
    The right answer to this question would be: don't insert serialized values in an RDBMS. This is the kind of thing that should summon raptors. Commented Sep 20, 2011 at 19:20
  • 1
    @timdev: json-escaping may in some situations correspond to SQL escaping, but depending on that will just burn you in the end. JSON uses backslashes - what if you're on a DB that doesn't recognizes backslashes and uses doubled-quotes for escape? e.g. '' instead of \'?
    – Marc B
    Commented Sep 20, 2011 at 19:20
  • 2
    While I agree with the principle expressed here (normal forms are good, using DB to structure is good, duh), any answer that starts with "No, you don't want..." sets off bells in my head. You do not have the full context of the asker's question, and believe it or not, they might just have an excellent reason to denormalize this particular data and store it in a single field. No, you are not omniscient; you do NOT know what the asker wants. Put your opinions in a comment, not an answer, please. Commented May 11, 2014 at 3:58
14

implode():

<?php
$string = implode('|',$types);

However, Incognito is right, you probably don't want to store it that way -- it's a total waste of the relational power of your database.

If you're dead-set on serializing, you might also consider using json_encode()

1
  • implode is limited to flat arrays
    – ahnbizcad
    Commented Jul 26, 2018 at 18:35
14

This one saves KEYS & VALUES

function array2string($data){
    $log_a = "";
    foreach ($data as $key => $value) {
        if(is_array($value))    $log_a .= "[".$key."] => (". array2string($value). ") \n";
        else                    $log_a .= "[".$key."] => ".$value."\n";
    }
    return $log_a;
}

Hope it helps someone.

0
9
$data = array("asdcasdc","35353","asdca353sdc","sadcasdc","sadcasdc","asdcsdcsad");

$string_array = json_encode($data);

now you can insert this $string_array value into Database

6

For store associative arrays you can use serialize:

$arr = array(
    'a' => 1,
    'b' => 2,
    'c' => 3
);

file_put_contents('stored-array.txt', serialize($arr));

And load using unserialize:

$arr = unserialize(file_get_contents('stored-array.txt'));

print_r($arr);

But if need creat dinamic .php files with array (for example config files), you can use var_export(..., true);, like this:

Save in file:

$arr = array(
    'a' => 1,
    'b' => 2,
    'c' => 3
);

$str = preg_replace('#,(\s+|)\)#', '$1)', var_export($arr, true));
$str = '<?php' . PHP_EOL . 'return ' . $str . ';';

file_put_contents('config.php', $str);

Get array values:

$arr = include 'config.php';

print_r($arr);
6

You can use serialize:

$array = array('text' => 'Hello world', 'value' => 100);
$string = serialize($array); // a:2:{s:4:"text";s:11:"Hello world";s:5:"value";i:100;}

and use unserialize to convert string to array:

$string = 'a:2:{s:4:"text";s:11:"Hello world";s:5:"value";i:100;}';
$array = unserialize($string); // 'text' => 'Hello world', 'value' => 100
5

there are many ways ,

two best ways for this are

$arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);
echo json_encode($arr);
//ouputs as
{"a":1,"b":2,"c":3,"d":4,"e":5}


$b = array ('m' => 'monkey', 'foo' => 'bar', 'x' => array ('x', 'y', 'z'));
$results = print_r($b, true); // $results now contains output from print_r
2
  • You're repeating answers that were already given. This does not add new value or new methods. Commented Jun 21, 2017 at 11:52
  • 2
    @Tschallacka yeah but very few answers on this post provide output ....
    – Daud Malik
    Commented Jun 22, 2017 at 14:58
2

Yet another way, PHP var_export() with short array syntax (square brackets) indented 4 spaces:

function varExport($expression, $return = true) {
    $export = var_export($expression, true);
    $export = preg_replace("/^([ ]*)(.*)/m", '$1$1$2', $export);
    $array = preg_split("/\r\n|\n|\r/", $export);
    $array = preg_replace(["/\s*array\s\($/", "/\)(,)?$/", "/\s=>\s$/"], [null, ']$1', ' => ['], $array);
    $export = join(PHP_EOL, array_filter(["["] + $array));
    
    if ((bool) $return) return $export; else echo $export;
}

Taken here.

1
  • Please read about what \R does in regex. Commented Feb 3, 2022 at 16:02
1

If you have an array (like $_POST) and need to keep keys and values:

function array_to_string($array) {
   foreach ($array as $a=>$b) $c[]=$a.'='.$b;
   return implode(', ',$c);
}

Result like: "name=Paul, age=23, city=Chicago"

Not the answer you're looking for? Browse other questions tagged or ask your own question.