Convert flat array to a delimited string to be saved in the database
Asked Answered
A

13

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
Aspergillum answered 20/9, 2011 at 19:13 Comment(5)
Please refrain from inserting serialized values into a database. Here's why: #7365303Mccollough
@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.Lockjaw
I think that this question should be reopened. It is useful question for beginners and I don't think it is off-topic.Lard
what if some of the values in array have chars |Desk
You can then escape those characters. Read it in here. php.net/manual/en/regexp.reference.escape.phpAntisocial
K
441

Use implode

implode("|",$type);
Kicker answered 20/9, 2011 at 19:14 Comment(3)
This is good unless you have nested arrays - which can happen with $_POST if you're using array-named form inputs.Lebar
with nested arrays just use a foreach it will work.Balmuth
@Balmuth 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.Deterioration
L
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!

Leet answered 20/9, 2011 at 19:16 Comment(7)
"Anything else is useless"... except perhaps normalizing the data.Centra
Rofl @ comment above me. As you say, blanket statements are almost always, unhelpful.Cotter
I'm glad you guys are entertained :)Leet
"Sweeping generalizations, as well as absolutes, are always wrong. Always." ;)Faubion
I like that this one keeps the keys. This is very useful for later use.Devlin
I have an array as response of API. One field in array contains encrypted data(AES CBC). I am not able to use json encode with it, and cannot convert it to string using any other means as well. Any suggestions?Rainout
Fail if array has accented characters, or non-utf8 ones.Bandit
D
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

Desk answered 3/10, 2013 at 10:46 Comment(3)
JFI in my use I had to call $data= json_decode($jsonString, true)Machree
second argument is optional, in most of the case it works without that.Desk
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.Comedown
U
46

One of the Best way:

echo print_r($array, true);
Uncial answered 18/6, 2014 at 11:24 Comment(4)
please elaborate on your answer, showing how it solves the problemCondillac
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.phpTransmittance
This one should be the best one since json_decode messes up with the format causing confusion.Hudgens
it was requested to store the string in the db, not to print itWhisky
N
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.

Needleful answered 20/9, 2011 at 19:14 Comment(9)
storing a serialized array is no better than storing a |-delimited array.Weisbrodt
sure it is, you dont have to escape the delimiters!Tengdin
@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.Needleful
@Chris: still have to escape the individual member elements, so it's simpler to just escape the entire imploded string once.Weisbrodt
@Needleful It also makes it nearly unreadable, harder to search, significantly harder to manipulate and wastes more space.Mccollough
@Marc B - no, you don't need to escape anything, just turn it into a string with json_encode() -- all escaping is automatic.Reticle
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.Mccollough
@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 \'?Weisbrodt
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.Attenuate
R
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()

Reticle answered 20/9, 2011 at 19:15 Comment(1)
implode is limited to flat arraysAgiotage
P
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.

Petepetechia answered 27/10, 2014 at 7:5 Comment(0)
C
9
$data = array("asdcasdc","35353","asdca353sdc","sadcasdc","sadcasdc","asdcsdcsad");

$string_array = json_encode($data);

now you can insert this $string_array value into Database

Crankshaft answered 17/11, 2017 at 13:22 Comment(0)
H
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);
Hertel answered 17/4, 2017 at 20:19 Comment(0)
J
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
Jelena answered 9/3, 2021 at 8:31 Comment(0)
B
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
Battaglia answered 21/6, 2017 at 11:38 Comment(2)
You're repeating answers that were already given. This does not add new value or new methods.Anzovin
@Anzovin yeah but very few answers on this post provide output ....Battaglia
C
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.

Ceroplastic answered 15/11, 2020 at 5:24 Comment(1)
Please read about what \R does in regex.Disendow
B
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"

Bandit answered 16/9, 2021 at 19:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.