Page 1 of 1

turning an array into a string then poping it into a db

Posted: Tue Oct 13, 2009 8:47 am
by gotornot
Hi im just wondering how you get a requested array into a single string then pop it into the db so far i got
print_r($_REQUEST['choice_name']);

whch echos

Array ( [0] => Colour=Blue [1] => Size=8 [2] => Neck Line=V )

I need it to look ready to enter into a db in a single field like this

Colour=Blue Size=8 Neck Line=V

Any ideas

Re: turning an array into a string then poping it into a db

Posted: Tue Oct 13, 2009 8:49 am
by Weiry

Code: Select all

$string =  implode($_REQUEST['choice_name']);
This is of course that you want everything just put in a string one item after another...

Re: turning an array into a string then poping it into a db

Posted: Tue Oct 13, 2009 8:55 am
by gotornot
thanks that worked great is there any way of adding something like <br. or [space] or - into it?

Re: turning an array into a string then poping it into a db

Posted: Tue Oct 13, 2009 9:06 am
by Weiry

Code: Select all

$myString = "";
$delimiter = " ";
foreach($_REQUEST['choice_name'] as $value){
   $myString .= $value.$delimiter;
}
print $myString;
But i wouldn't use a space for your delimiter (separating your array values), you would be better off using a comma or colon etc.
So you would change

Code: Select all

$delimiter = " ";
to be

Code: Select all

$delimiter = ":";
as an example

Re: turning an array into a string then poping it into a db

Posted: Tue Oct 13, 2009 9:36 am
by gotornot
how do i add the 2 together tho?
Ive done as you suggested it just keeps saying Array at teh begining its SO ANNOYING

Re: turning an array into a string then poping it into a db

Posted: Tue Oct 13, 2009 11:50 am
by jackpf
What code are you using?

Re: turning an array into a string then poping it into a db

Posted: Tue Oct 13, 2009 2:00 pm
by PHPHorizons
Hello gotornot,

Using implode will not get you the format you specified in the op.

Colour=Blue Size=8 Neck Line=V
McInfo has pointed out that you can use serialize() to convert an array to a string, and unserialize() to convert back to an array. This is the prefered way to convert arrays to strings when you need to preserve the keys (implode blows away your keys).

If you are using php >= 5.2, then json_encode() and json_decode() are better than serialize/unserialize in many cases. (just make sure to use "true" for the second parameter of json_decode in order to get an array instead of an object: json_decode($string, true))

Hope that helps.