Array to String PHP?

PhpArraysString

Php Problem Overview


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

Php Solutions


Solution 1 - Php

Use implode

implode("|",$type);

Solution 2 - Php

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!

Solution 3 - Php

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

Solution 4 - Php

One of the Best way:

echo print_r($array, true);

Solution 5 - Php

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.

Solution 6 - Php

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()

Solution 7 - Php

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.

Solution 8 - Php

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

$string_array = json_encode($data);

now you can insert this $string_array value into Database

Solution 9 - Php

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);

Solution 10 - Php

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

Solution 11 - Php

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

Solution 12 - Php

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.

Solution 13 - Php

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"

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionPhilip KirkbrideView Question on Stackoverflow
Solution 1 - PhpNiet the Dark AbsolView Answer on Stackoverflow
Solution 2 - PhpJakubView Answer on Stackoverflow
Solution 3 - PhpsumitView Answer on Stackoverflow
Solution 4 - Phpvvkatwss vvkatwssView Answer on Stackoverflow
Solution 5 - PhpIncognitoView Answer on Stackoverflow
Solution 6 - PhptimdevView Answer on Stackoverflow
Solution 7 - PhpAnte BraovicView Answer on Stackoverflow
Solution 8 - PhpAkbar MirsiddikovView Answer on Stackoverflow
Solution 9 - PhpGuilherme NascimentoView Answer on Stackoverflow
Solution 10 - PhpHOSSEIN BView Answer on Stackoverflow
Solution 11 - PhpDaud MalikView Answer on Stackoverflow
Solution 12 - PhpSerhii PopovView Answer on Stackoverflow
Solution 13 - PhpArvyView Answer on Stackoverflow