363

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
mickmackusa
  • 43,625
  • 12
  • 83
  • 136
Philip Kirkbride
  • 21,381
  • 38
  • 125
  • 225
  • 25
    Please refrain from inserting serialized values into a database. Here's why: http://stackoverflow.com/questions/7364803/storing-arrays-in-the-database/7364834#7364834 – NullUserException Sep 20 '11 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. – AngryHacker Sep 21 '11 at 06: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 Feb 23 '14 at 16:47
  • 1
    what if some of the values in array have chars | – Sumit Kumar May 20 '14 at 11:22
  • You can then escape those characters. Read it in here. http://php.net/manual/en/regexp.reference.escape.php – FortuneSoldier Feb 26 '18 at 13:03

13 Answers13

440

Use implode

implode("|",$type);
Kees de Kooter
  • 7,078
  • 5
  • 38
  • 45
Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
  • 18
    This is good unless you have nested arrays - which can happen with `$_POST` if you're using array-named form inputs. – Leith Oct 24 '16 at 04:47
  • with nested arrays just use a foreach it will work. – devasia2112 Mar 26 '19 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 Aug 13 '21 at 05:35
277

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!

Jakub
  • 20,418
  • 8
  • 65
  • 92
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

Sumit Kumar
  • 1,855
  • 19
  • 19
46

One of the Best way:

echo print_r($array, true);
T.Todua
  • 53,146
  • 19
  • 236
  • 237
vvkatwss vvkatwss
  • 3,345
  • 1
  • 21
  • 24
  • 13
    please elaborate on your answer, showing how it solves the problem – Our Man in Bananas Jun 18 '14 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: http://php.net/manual/en/function.print-r.php – Garrett Sep 02 '16 at 18:42
  • 1
    This one should be the best one since `json_decode` messes up with the format causing confusion. – Aminah Nuraini Jun 16 '17 at 19:28
  • it was requested to store the string in the db, not to print it – Mark Jul 02 '20 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.

Nisse Engström
  • 4,738
  • 23
  • 27
  • 42
Incognito
  • 20,537
  • 15
  • 80
  • 120
  • storing a serialized array is no better than storing a `|`-delimited array. – Marc B Sep 20 '11 at 19:16
  • 2
    sure it is, you dont have to escape the delimiters! – Chris G. Sep 20 '11 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 Sep 20 '11 at 19:17
  • @Chris: still have to escape the individual member elements, so it's simpler to just escape the entire imploded string once. – Marc B Sep 20 '11 at 19:18
  • @Incognito It also makes it nearly unreadable, harder to search, significantly harder to manipulate and wastes more space. – NullUserException Sep 20 '11 at 19:19
  • @Marc B - no, you don't need to escape anything, just turn it into a string with json_encode() -- all escaping is automatic. – timdev Sep 20 '11 at 19:19
  • 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](http://xkcd.com/292/). – NullUserException Sep 20 '11 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 Sep 20 '11 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. – system PAUSE May 11 '14 at 03:58
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.

T.Todua
  • 53,146
  • 19
  • 236
  • 237
Ante Braovic
  • 457
  • 4
  • 13
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()

timdev
  • 61,857
  • 6
  • 82
  • 92
9
$data = array("asdcasdc","35353","asdca353sdc","sadcasdc","sadcasdc","asdcsdcsad");

$string_array = json_encode($data);

now you can insert this $string_array value into Database

slfan
  • 8,950
  • 115
  • 65
  • 78
Akbar Soft
  • 1,028
  • 10
  • 19
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);
Protomen
  • 9,471
  • 9
  • 57
  • 124
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
HOSSEIN B
  • 301
  • 2
  • 7
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
Akbar Soft
  • 1,028
  • 10
  • 19
Daud Malik
  • 61
  • 1
  • 1
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.

Serhii Popov
  • 3,326
  • 2
  • 25
  • 36
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"

Arvy
  • 1,072
  • 2
  • 16
  • 29