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
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!
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
One of the Best way:
echo print_r($array, true);
json_decode
messes up with the format causing confusion.
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.
''
instead of \'
?
<?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()
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.
$data = array("asdcasdc","35353","asdca353sdc","sadcasdc","sadcasdc","asdcsdcsad");
$string_array = json_encode($data);
now you can insert this $string_array value into Database
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);
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
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
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.
\R
does in regex.
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"
$types = ['a','b','c'];
$string = implode(",",$types);
echo $string;
answer = "a,b,c".
Success story sharing
$_POST
if you're using array-named form inputs.